như được hiển thị trong ví dụ bên dưới, tôi muốn MyComponent tự động đính kèm sự kiện "onClick" vào con của nó. Sự kiện onClick sẽ kích hoạt alertView để có thể gọi phương thức phần tử được nhấp "getValue".React.js: đính kèm sự kiện từ cha mẹ cho trẻ em
JSFiddle: http://jsfiddle.net/2g638bp8/
Làm cách nào để thực hiện việc này? Cảm ơn
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')
);
Cảm ơn cho câu trả lời hữu ích này - là nó bây giờ giá trị cập nhật nó và fiddle của bạn để sử dụng 'React.cloneElement' thay vì ..? (do 'cloneWithProps' không được chấp nhận) –