我试图找到正确的方法来定义一些组件,这些组件可以以通用的方式使用:

<Parent>
  <Child value="1">
  <Child value="2">
</Parent>

当然,在父组件和子组件之间呈现有一个逻辑,您可以想象<select>和<option>是这个逻辑的一个例子。

这是为了解决这个问题的一个虚拟实现:

var Parent = React.createClass({
  doSomething: function(value) {
  },
  render: function() {
    return (<div>{this.props.children}</div>);
  }
});

var Child = React.createClass({
  onClick: function() {
    this.props.doSomething(this.props.value); // doSomething is undefined
  },
  render: function() {
    return (<div onClick={this.onClick}></div>);
  }
});

问题是无论何时使用{this.props。Children}定义一个包装器组件,如何将某些属性传递给它的所有子组件?


当前回答

允许你进行属性转移的最好方法是像函数模式一样的子元素 https://medium.com/merrickchristensen/function-as-child-components-5f3920a9ace9

代码片段:https://stackblitz.com/edit/react-fcmubc

例子:

const Parent = ({ children }) => {
    const somePropsHere = {
      style: {
        color: "red"
      }
      // any other props here...
    }
    return children(somePropsHere)
}

const ChildComponent = props => <h1 {...props}>Hello world!</h1>

const App = () => {
  return (
    <Parent>
      {props => (
        <ChildComponent {...props}>
          Bla-bla-bla
        </ChildComponent>
      )}
    </Parent>
  )
}

其他回答

这是你所要求的吗?

var Parent = React.createClass({
  doSomething: function(value) {
  }
  render: function() {
    return  <div>
              <Child doSome={this.doSomething} />
            </div>
  }
})

var Child = React.createClass({
  onClick:function() {
    this.props.doSome(value); // doSomething is undefined
  },  
  render: function() {
    return  <div onClick={this.onClick}></div>
  }
})

最巧妙的方法是:

    {React.cloneElement(this.props.children, this.props)}

这个答案是w.r.t. React v17.x…

使用子函数作为一个函数,并将道具传递给它作为渲染道具模式,如下所示

 <ParentComponent {...anyAdditionalProps}>
   {
     (actualPropsToPass) => <ChildComponent>{children(actualPropsToPass)}</ChildComponent>
   }
 </ParentComponent>

只是要确保,实际的,要投影的内容必须像渲染道具模式中的函数一样添加,以适应在子函数中作为道具传递的参数。

用新道具克隆孩子

你可以使用React。子元素遍历子元素,然后使用React.cloneElement用新道具(浅合并)克隆每个元素。

请参阅代码注释,为什么我不推荐这种方法。

const Child = ({childName, sayHello}) => ( <button onClick={() => sayHello(childName)}>{childName}</button> ); 函数父({children}) { //我们将sayHello函数传递给子元素。 函数sayHello(childName) { console.log(' Hello from ${childName} the child '); } const childrenWithProps = React.Children。映射(children, child => { //检查isValidElement是安全的方法,可以避免 // typescript错误。 if (React.isValidElement(child)) { 返回的反应。cloneElement(child, {sayHello}); } 返回的孩子; }); 返回< div > {childrenWithProps} < / div > } 函数App() { //这种方法不太类型安全,Typescript不友好 //看起来像你试图渲染' Child '没有' sayHello '。 //这也会让代码的读者感到困惑。 回报( <父> <Child childName="Billy" /> <Child childName="Bob" /> 父> < / ); } ReactDOM。render(<App />, document.getElementById("container")); < script src = " https://unpkg.com/react@17 umd格式/ react.production.min.js " > < /脚本> < script src = " https://unpkg.com/react-dom@17 umd格式/ react-dom.production.min.js " > < /脚本> < div id = "容器" > < / div >

将子函数作为函数调用

或者,你可以通过渲染道具将道具传递给孩子们。在这种方法中,children(可以是children或任何其他道具名)是一个函数,它可以接受你想传递的任何参数,并返回实际的子函数:

const Child = ({childName, sayHello}) => ( <button onClick={() => sayHello(childName)}>{childName}</button> ); 函数父({children}) { 函数sayHello(childName) { console.log(' Hello from ${childName} the child '); } //这个组件的children必须是一个函数 //返回实际的子节点。我们可以通过 //它的参数然后传递给他们作为道具(在这个 //如果我们传递' sayHello ')。 返回< div >{孩子(sayHello)} < / div > } 函数App() { // sayHello是我们在Parent中传递的参数 //我们现在传递到Child。 回报( <父> {(sayHello) => ( <反应。片段> <Child childName="Billy" sayHello={sayHello} /> <Child childName="Bob" sayHello={sayHello} /> < /反应。片段> )} 父> < / ); } ReactDOM。render(<App />, document.getElementById("container")); < script src = " https://unpkg.com/react@17 umd格式/ react.production.min.js " > < /脚本> < script src = " https://unpkg.com/react-dom@17 umd格式/ react-dom.production.min.js " > < /脚本> < div id = "容器" > < / div >

向嵌套子节点传递道具

随着React Hooks的更新,你现在可以使用React了。createContext和useContext。

import * as React from 'react';

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

functional Parent(props) {
  const doSomething = React.useCallback((value) => {
    // Do something here with value
  }, []);

  return (
     <MyContext.Provider value={{ doSomething }}>
       {props.children}
     </MyContext.Provider>
  );
}
 
function Child(props: { value: number }) {
  const myContext = React.useContext(MyContext);

  const onClick = React.useCallback(() => {
    myContext.doSomething(props.value);
  }, [props.value, myContext.doSomething]);

  return (
    <div onClick={onClick}>{props.value}</div>
  );
}

// Example of using Parent and Child

import * as React from 'react';

function SomeComponent() {
  return (
    <Parent>
      <Child value={1} />
      <Child value={2} />
    </Parent>
  );
}

反应。createContext发光的地方React。cloneElement case不能处理嵌套组件

function SomeComponent() {
  return (
    <Parent>
      <Child value={1} />
      <SomeOtherComp>
        <Child value={2} />
      </SomeOtherComp>
    </Parent>
  );
}