reactjs - 在 React 中使用包装组件来传递 props 可以吗?

标签 reactjs react-redux

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。

https://pastebin.com/G3PgVxLn

最佳答案

也许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,...

将 props 传递给子项

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 而不是少数(mouseonMouseMove)

关于reactjs - 在 React 中使用包装组件来传递 props 可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51657890/

相关文章:

javascript - 在使用 Tailwind CSS 时从 `ListBox` 设置 `@headlessui/react` 上的最大内容以获取选项的最大宽度?

javascript - 未从 Redux 中的子组件获取 props

javascript - 使用react-native构建android应用程序时如何解决命令节点问题?

reactjs - Redux-saga 与 Internet Explorer

javascript - ReactJS动态路由没有 "/"

javascript - 将回调传递给 redux 异步操作是否被认为是好的做法?

javascript - setState 没有按预期更新

reactjs - 如何使用钩子(Hook)显示和隐藏 react 组件

reactjs - 采用 React-bootstrap 样式的 Formik

javascript - 如何清除 react 状态数组?