如何将道具传递给{this.props.children} [英] How to pass props to {this.props.children}

查看:170
本文介绍了如何将道具传递给{this.props.children}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to find the proper way to define some components which could be used in a generic way:

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

当然,在父组件和子组件之间进行渲染是有逻辑的,你可以想象< select> < option> 作为此逻辑的示例。

There is a logic going on for rendering between parent and children components of course, you can imagine <select> and <option> as an example of this logic.

这是一个用于问题目的的虚拟实现:

This is a dummy implementation for the purpose of the question:

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} 定义一个包装器组件,如何将一些属性传递给它的所有子组件?

The question is whenever you use {this.props.children} to define a wrapper component, how do you pass down some property to all its children?

推荐答案

你可以使用 React.Children 迭代子项,然后使用new克隆每个元素使用 React.cloneElement 的道具(浅层合并)例如:

You can use React.Children to iterate over the children, and then clone each element with new props (shallow merged) using React.cloneElement e.g:

const Child = ({ doSomething, value }) => (
  <div onClick={() => doSomething(value)}>Click Me</div>
);

class Parent extends React.PureComponent {
  doSomething = (value) => {
    console.log('doSomething called by child with value:', value);
  }

  render() {
    const { children } = this.props;

    const childrenWithProps = React.Children.map(children, child =>
      React.cloneElement(child, { doSomething: this.doSomething })
    );

    return <div>{childrenWithProps}</div>
  }
};

ReactDOM.render(
  <Parent>
    <Child value="1" />
    <Child value="2" />
  </Parent>,
  document.getElementById('container')
);

小提琴: https://jsfiddle.net/2q294y43/2/

这篇关于如何将道具传递给{this.props.children}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆