我正试图把我的头脑集中在如何重组的工作上。虽然我理解它的基本概念,但我在使用withProps函数时遇到了问题。如果我尝试使用它来装饰一个组件的每个子组件,使用附加的道具,它就会失败。我所做的是:
const decorateChild = withProps({ /* some additional props */ });
// ... later on
{ React.Children.map(this.props.children, decorateChild) }它根本不起作用。我不得不去做React.cloneElement。你能帮我一下吗。下面是是一个沙箱.请注意WrappedComponent.js号码9
编辑(我有问题的代码.)
所以这很好用:
const decorateChild = actions => child =>
typeof child === "function"
? child(actions)
: React.cloneElement(child, actions);然而,我想让它用重新组合的方式来写。正如我前面说过的,如果我不使用cloneElement,而是尝试执行withProps(action)(child),它将不能工作,->什么都不会呈现。如果我试图强迫组件通过withProps(action)(child)()呈现,应用程序就会崩溃。
通常,我想知道如何使用重新组合来表达整个WrappedComponent.js。关于当前实现,我不喜欢的是我必须手动管理ref,因为我使用的底层组件(这里是Wrap)需要它,这是我无法更改的东西(第三方库)。我也想用重新组合来处理它。
我希望这个小小的解释能使我想要的更清楚一点。
发布于 2018-07-22 00:08:39
withProps返回输入是另一个组件的函数(请注意,这里的child是组件的输出,即表示它的不透明JS对象),decorateChild(action)也应该返回不透明的数据结构,这说明了为什么需要再次调用它作为函数。
以下可能比您使用React.cloneElement时做的更糟糕,但它有效:
const decorateChild = actions => child => {
const Component = (props) => ({ ...child, props: { ...child.props, ...props } })
return typeof child === "function"
? child(actions)
: withProps(actions)(Component)();
// this also works
// : withProps(actions)((props) => React.cloneElement(child, props))();
};https://stackoverflow.com/questions/51455580
复制相似问题