[英]Is it ok to use a wrapper component to pass props in React?
export function injectProps() {
const injects = {store: new Store()}; // some store
return function (Component) {
return class Proxy extends React.Component {
render() {
return React.createElement(Component, {
...injects,
...this.props,
});
}
};
}
}
Is it ok to use this instead of Redux or Context API with React? 可以在React中使用它而不是Redux或Context API吗?
Update: I think I missed to point out my expectation. 更新:我想我没有指出我的期望。 I'm actually passing some service(http, localStorage) to childrens only when they asks for it.
我实际上只是在儿童要求时才将某些服务(http,localStorage)传递给儿童。 It's not only about the store as services don't have any state.
这不仅与商店有关,因为服务没有任何状态。 But I also need to pass store through it.
但是我也需要通过它。
Maybe this tweet by the Dan Abramov (React maintainer) might help. 也许这种鸣叫 由丹·阿布拉莫夫(阵营维护者)可能的帮助。
I understand it was probably not the point of the article.
我了解这可能不是本文的重点。 But I see people reaching for Context or Redux because they don't realize components can take any children — and that often removes the need for deep prop passing.
但是我看到人们喜欢Context或Redux的原因是他们没有意识到组件可以带走任何孩子,而这通常消除了对深入传递道具的需求。 Would be great to highlight!
突出显示会很棒!
And Dave Ceddia posted a relavant React documentation link. 戴夫·塞迪亚(Dave Ceddia)发布了相关的React文档链接。
Composition vs Inheritance 组合与继承
You can read upon those two. 您可以阅读这两本书。
And here is a demo Nicolas Marcora created to show me how to pass properties to child/children. 这是Nicolas Marcora制作的演示,向我展示了如何将财产传递给孩子。
You can pass props to children using React.cloneElement(child,...
您可以使用
React.cloneElement(child,...
Working demo on StackBlitz . StackBlitz上的工作演示。
export default class WithMouse extends React.Component {
state = { x: 0, y: 0 }
handleMouseMove = event => { ... }
render() {
const { children } = this.props
const childElements = React.Children.map(children, child =>
React.cloneElement(child, {
mouse: this.state,
onMouseMove: this.handleMouseMove
})
)
return <div>
{ childElements }
</div>
}
}
You can use WithMouse class to pass props downward to all children and use it like following. 您可以使用WithMouse类将道具向下传递给所有孩子,并像下面那样使用它。
class App extends Component {
...
render() {
return (
<WithMouse>
<MouseTracker />
</WithMouse>
);
}
}
MouseTracker has access to props passed from WithMouse
so you can just use it without directly passing it manually. MouseTracker可以访问从
WithMouse
传递的道具,因此您可以直接使用它而无需直接手动传递它。
You can probably go further and pass all props instead of a few ( mouse
, onMouseMove
) 您可能可以走得更远,并传递所有道具,而不是几个道具(
mouse
, onMouseMove
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.