,如下面的示例所示,我希望MyComponent動態地將「onClick」事件附加到其子項。 onClick事件應該觸發alertView,該alertView應該能夠調用單擊元素方法「getValue」。React.js:將事件從父項添加到子項
的jsfiddle:http://jsfiddle.net/2g638bp8/
如何做到這一點?謝謝
var MyComponent = React.createClass({
alertValue: function() {
// RETRIEVE THE CHILD HERE
alert(child.getValue());
},
render: function() {
var children = React.Children.map(this.props.children, function (c, index) {
return React.addons.cloneWithProps(c, {
ref: 'child-' + index
});
});
return (
<div>
{children}
</div>
);
}
});
var MySubComponent = React.createClass({
getValue: function() {
return this.props.val;
},
render: function() {
return (
<div>{this.props.val}</div>
);
}
});
React.render(
<div>
<MyComponent>
<MySubComponent val="1" />
<MySubComponent val="2" />
<MySubComponent val="3" />
</MyComponent>
</div>,
document.getElementById('container')
);
感謝這個有用的答案 - 是現在值得更新它和你的小提琴使用'React.cloneElement'代替..? (由於'cloneWithProps'被棄用) – 2016-08-05 10:31:35