javascript - 将 Prop 传递给它的所有 child

标签 javascript reactjs

我正在实现一个嵌套组件,我的所有组件都需要有 variable 属性,现在我有:

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

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

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

我需要从 Child1Child2 访问variable prop

最佳答案

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

I highly recommend using React.createContext in React 16.3+ since this is exactly what React Context is meant for. Its also especially helpful if you have flow to keep prop type checking working properly.

Note in React 16.6 its even easier to use context by using 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>
  }
}

This is a quick example of how to do this without React Context and using 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})
      )
    );
  }
}

关于javascript - 将 Prop 传递给它的所有 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49726000/

相关文章:

javascript - 强制 ng-include 重新渲染

javascript - C#和javascript之间的加密结果差异

javascript - .show() 以相同形式的字段值为条件的元素

reactjs - React 组件订阅太晚了。如何避免失去第一场比赛?

javascript - 什么时候将此关键字绑定(bind)到 react 中的事件处理程序?

reactjs - 使用 Ethersjs 获取 ETH 余额

javascript - 从 React 中的异步调用批量状态更新的最佳方法是什么?

javascript - 有人能解释一下为什么我的菜单项中有背景边框吗?

javascript - 通过移动浏览器访问 Google AAID (Javascript)

reactjs - 未找到属性 - flowtype/react,使用此