首页 > 解决方案 > 在 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)传递给孩子们。这不仅仅是关于商店,因为服务没有任何状态。但我也需要通过它来存储。

https://pastebin.com/G3PgVxLn

标签: reactjsreact-redux

解决方案


也许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因此您可以直接使用它而无需手动直接传递它。

您可能可以走得更远并传递所有道具而不是一些(mouseonMouseMove


推荐阅读