React:如何使用通常的哑组件连接可重用组件

时间:2016-06-20 09:08:55

标签: reactjs components middleware flux

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

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

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

  2. 在提供重新映射React.cloneElement(children, props)的功能时返回props

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

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

  5. 您为自己的应用选择了哪种方法?为什么?请分享想法。

    听到React家伙的意见会很高兴。

1 个答案:

答案 0 :(得分:-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.