如何将道具传递给{this.props.children}

点点圈 提交于 2020-08-07 21:44:54

问题:

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>

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. 当然,在父组件和子组件之间存在渲染逻辑,您可以想象<select><option>作为此逻辑的示例。

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>);
  }
});

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? 问题是,每当您使用{this.props.children}定义包装器组件时,如何将某些属性传递给其所有子级?


解决方案:

参考一: https://stackoom.com/question/2BpAo/如何将道具传递给-this-props-children
参考二: https://oldbug.net/q/2BpAo/How-to-pass-props-to-this-props-children
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!