reactjs - 在 React 中使用包装器组件传递 props 可以吗?
问题描述
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 吗?
更新:我想我错过了指出我的期望。我实际上只是在孩子们要求时才将一些服务(http,localStorage)传递给孩子们。这不仅仅是关于商店,因为服务没有任何状态。但我也需要通过它来存储。
解决方案
也许Dan Abramov(React 维护者)的这条推文可能会有所帮助。
我知道这可能不是这篇文章的重点。但我看到人们使用 Context 或 Redux 是因为他们没有意识到组件可以带任何孩子——这通常消除了对深度 prop 传递的需要。将是伟大的突出!
Dave Ceddia发布了一个相关的 React 文档链接。
组合与继承
你可以阅读这两个。
这是一个演示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类将道具向下传递给所有孩子并像下面一样使用它。
class App extends Component {
...
render() {
return (
<WithMouse>
<MouseTracker />
</WithMouse>
);
}
}
MouseTracker可以访问从中传递的道具,WithMouse
因此您可以直接使用它而无需手动直接传递它。
您可能可以走得更远并传递所有道具而不是一些(mouse
,onMouseMove
)
推荐阅读
- r - if (...) 参数中的错误长度为零。NO 空值
- python - Beam:“通道”对象没有“关闭”属性
- java - 插入数据库后,第一次不读取值
- android - 我如何在 mongo db 中搜索一个表,为我的 android 应用程序生成这个所需的 url?
- tensorflow - 如何解决 Keras conv2d 输入形状错误?
- python - 手动检查井字游戏状态的数量
- javascript - JavaScript & HTML - 重用来自 fetch() 的数据
- html - 排列第三级下拉导航的问题
- c - 我不知道为什么 else if 语句没有发生
- aframe - WebVR 已弃用,那么是否会有适用于 webXR 的 A-frame 版本?