如何在react中将信息传递给嵌套组件?

IT技术 javascript reactjs
2021-05-25 07:13:05

说我有

<component1>
     <component2>
           <component3>
                 <component4>

(其中 component1 有一个子 component2,component2 有一个子 component3,component3 有一个子 component4)

并说我想将一些东西从 component1 传递到 component4 。我需要在链上传递props吗?所以组件1 -> 组件2 -> 组件3 -> 组件4

?

请注意: 这些组件不在同一个文件中。所以在 component1.js 中我指的<component2>是 component2.js 中我指的是<component3>等等。

3个回答

您在这里有 2 个主要选项:

  1. 把props传下来。
  2. 使用contextAPI

随着props你也得到了两个主要的选项:

  1. 您可以隐式传递props

    <Parent>
      <ChildOne {...props}>
        <ChildTwo {...props}>
        </ChildTwo>
      </ChildOne>
    </Parent>
    

    隐式props的运行片段:

  2. 或者做明确的

    <Parent>
      <ChildOne propOne={propOne}>
        <ChildTwo propOne={propOne}>
        </ChildTwo>
      </ChildOne>
    </Parent>
    

    显式props的运行片段:


至于上下文 API,您可以跳过级别并从祖父母那里“抢夺”props。
这就是react-redux幕后的事情

上下文 API 的运行示例

请注意,此示例使用的是 react v15,其语法React.PropTypes已更改,因为 react v16PropTypes不再是react库的一部分,而是被提取到另一个库中prop-types

另请注意,文档建议不要使用上下文 API

如果您不是经验丰富的 React 开发人员,请不要使用上下文。通常有更好的方法来实现功能,只需使用 props 和 state。

您可以使用 React 的内置功能Context API,尽管我不建议您过分依赖它,因为这可能会被弃用或成为一个完整的稳定功能。截至目前,Facebook 在其文档WARNING 中警告用户没有那个小问题,API 非常棒,有助于维护整洁的代码,而无需一直将 props 发送给预期的后代。

上下文API

组件 1

class Component1 extends React.Component {
  getChildContext() {
    return {
      yourProp: "someValue" // you can also add a function like yourProp: someFunc
    };
  }

  render() {
    <Component2 />
  }
}

Component1.childContextTypes = {
  yourProp: PropTypes.string
};

组件 2

class Component2 extends React.Component {
  render() {
    return (
      <Component3 />
    );
  }
}

组件 3

class Component3 extends React.Component {
  render() {
    return (
      <Component4 />
    );
  }
}

组件4

class Component4 extends React.Component {
  render() {
    return (
      <div>
        {this.context.yourProp}      
      </div>
    );
  }
}

Component4.contextTypes = {
  yourProp: PropTypes.string
};

如果您不选择使用它,则有很多策略。

  • 还原
  • 事件发射器
  • 将props一直传递给后代

是的,如果只使用 React,您需要通过每个组件传递 props,即使组件不使用该 props。因此,在您的示例中, control2 和 control3 不关心props,但需要将其传递下去。以下是您需要执行的操作。

<Control1 test={this.state.test}>
  <Control2 test={this.props.test}>
    <Control3 test={this.props.test}>
      <Control4 test={this.props.test} />
    </Control3>
  </Control2>
</Control1>

这可能会变得很麻烦,所以这是redux可以提供帮助的情况。