将道具传递给所有孩子

时间:2018-04-09 05:15:05

标签: javascript reactjs

我正在实现一个嵌套组件,我的所有组件都需要变量道具,现在我有:

<Parent variable="myVariable">
   <Child1 variable="myVariable" />
   <Child2 variable="myVariable" />
</Parent>

但我不想直接将道具传递给每个组件,我需要这样的东西:

<Parent variable="myVariable">
    <Child1 />
    <Child2 />
</Parent>

我需要从 Child1 Child2 访问变量道具

2 个答案:

答案 0 :(得分:8)

有两种解决方案可以做到这一点。在父组件中使用 React.createContext React.cloneElement

  

我强烈建议在 React 16.3 + 中使用 React.createContext ,因为这正是React Context的意思。如果您有流程以使prop类型检查正常工作,它也特别有用。

     

请注意 React 16.6 ,使用 contextType 更容易使用上下文。

https://reactjs.org/docs/context.html

(或使用create-react-context https://github.com/jamiebuilds/create-react-context)如果您不是最新的。

// parentFile.js
import * as React from 'react';

export const MyContext = React.createContext(); // React.createContext accepts a defaultValue as the first param

type Props = {
  variable: string,
  children: React.Node
};

class Parent extends React.Component<Props> {
  render() {
    return (
       <MyContext.Provider value={{ variable: this.props.variable }}>
         {this.props.children}
       </MyContext.Provider>
    );
  }
}

class Child1 extends Component<{}> {
  static contextType = MyContext;
  render() {
    return (<div>{this.context.variable}</div>);
  }
}

// IF you have a child in a different file make sure you import the correct consumer
// child2.js
import * as React from 'react';
import { MyContext } from './parentFile';

class Child2 extends Component<{}> {
  static contextType = MyContext;
  render() {
    return (<span>{this.context.variable}</span>);
  }
}

React.createContext在这里可以处理嵌套组件

// Example of using Parent and Child

import * as React from 'react';

class SomeComponent extends React.Component<{}> {

  render() {
    <Parent variable="test">
      <Child1 />
      { /* Previously you couldn't use 
           React.cloneElement to handle the nested case */ }
      <SomeOtherComp>
        <Child2 />
      </SomeOtherComp>
    </Parent>
  }
}
  

这是一个快速示例,说明如何在没有 React Context 和使用 React.cloneElement

的情况下执行此操作
import * as React from 'react';

class Parent extends Component {
  render() {
    const { children, props } = this.props;
    return (
      React.Children.map(children, child =>
        React.cloneElement(child, {...props})
      )
    );
  }
}

答案 1 :(得分:2)

您可以将孩子作为道具传递给父母:

   class Wrapper extends React.Component {
     render() {
      return (
        this.props.wraps.map(El => <El {...this.props} />);
     };
    }
  }

所以你可以这样做:

  <Wrapper wraps = {[Child1, Child2]} variable = "whatever" />