如何將道具傳遞給 {this.props.children} - How to pass props to {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>

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://en.stackoom.com/question/2BpAo
參考二: https://stackoom.com/question/2BpAo
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章