首页 文章

React:如何将可重用组件与通常的哑组件连接起来

提问于
浏览
0

当我开发基于React的Web应用程序时,我经常将组件分为智能和哑,以及可重用和自定义 . 可重复使用的部件可以是自给自足的,例如, <RedButton><CustomSelect> 但它们也可以是中间件组件,例如 <FluxStoreBinder> . 中间件组件在向其添加某些功能时呈现其 children ,通常是订阅 - 从Flux商店读取或从其中包含其他有状态的内容 . 但是,需要一些额外的工作来将可重用的智能中间件组件连接到哑组件,因为它们的道具不太可能匹配 . 例如 . a <FluxStoreReader> 可能"return"名为 data 的属性,而 <ToDoList> 类型的子项需要 toDoItems .

我想问的问题是如何告诉中间件组件以哪种方式呈现哪些内容 . 什么是正确和推荐的方法?目前,我已经看到了三种告诉中间件组件如何呈现其子代的方法:

  • 通过道具提供功能,例如 render={({arg1}) => <Child prop1={arg1}/>} . 功能是:您可以在此功能中访问自己的州/道具/等;你可以处理和重新绘制道具;您可以根据条件指定要渲染的子项;您可以为子项设置所需的道具,而无需通过中间件组件进行代理 .

  • 通过返回 React.cloneElement(children, props) ,同时提供重映射功能 props .

  • 通过渲染 React.cloneElement(children, props) 并将收到的道具代理到孩子身上 . 纯组件方法,无回调 . 这个没有上述2的功能/灵活性,还需要一些额外的工作:你需要在你的中间件和它的孩子之间的另一个中间件来重新映射道具 .

  • Mike Tronic建议的第四个选项是使用高阶组件,它们基本上是组件工厂,其中一个必需参数是子组件类 . 它与#3几乎相同 - 但是一旦你运行工厂,你甚至无法改变孩子的类型 .

您为应用选择了哪种方法?为什么?请分享想法 .

很高兴听到React的观点 .

1 回答

  • -1
    check https://www.youtube.com/watch?v=ymJOm5jY1tQ
    http://rea.tech/reactjs-real-world-examples-of-higher-order-components/ and 
    http://www.darul.io/post/2016-01-05_react-higher-order-components
    What are Higher Order Components?
    A Higher Order Component is just a React Component that wraps another one.
    This pattern is usually implemented as a function, which is basically a class factory (yes, a class factory!), that has the following signature in haskell inspired pseudocode
    hocFactory:: W: React.Component => E: React.Component
    Where W (WrappedComponent) is the React.Component being wrapped and E (Enhanced Component) is the new, HOC, React.Component being returned.
    The “wraps” part of the definition is intentionally vague because it can mean one of two things:
    Props Proxy: The HOC manipulates the props being passed to the WrappedComponent W,
    Inheritance Inversion: The HOC extends the WrappedComponent W.
    We will explore this two patterns in more detail.
    What can I do with HOCs?
    At a high level HOC enables you to:
    Code reuse, logic and bootstrap abstraction
    Render Highjacking
    State abstraction and manipulation
    Props manipulation
    We will see this items in more detail soon but first, we are going to study the ways of implementing HOCs because the implementation allows and restricts what you can actually do with an HOC.
    

相关问题