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,
});
}
};
}
}
在 React 中使用它代替 Redux 或 Context API 可以吗?
更新:我想我错过了指出我的期望。实际上,只有当 children 要求时,我才会将一些服务(http、localStorage)传递给他们。这不仅仅与商店有关,因为服务没有任何状态。但我还需要通过它传递 store。
最佳答案
也许this tweet由 Dan Abramov(React 维护者)撰写的文章可能会有所帮助。
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. Would be great to highlight!
和Dave Ceddia发布了相关的 React 文档链接。
Composition vs Inheritance
您可以阅读这两篇文章。
这是一个演示 Nicolas Marcora创建是为了向我展示如何将属性传递给子级。
您可以使用 React.cloneElement(child,...
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>
}
}
您可以使用WithMouse类将 props 向下传递给所有 child 并像下面一样使用它。
class App extends Component {
...
render() {
return (
<WithMouse>
<MouseTracker />
</WithMouse>
);
}
}
MouseTracker可以访问从 WithMouse
传递的 props,因此您可以直接使用它,而无需直接手动传递它。
您可能可以更进一步,传递所有 Prop 而不是少数(mouse
、onMouseMove
)
关于reactjs - 在 React 中使用包装组件来传递 props 可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51657890/