You cannot call methods on child components in React. You can only set properties. ( child is actually a ReactElement that contains information about the class and its related properties. This is not an instance of the component that you created).
So, you could think of it a little different and move onClick to MySubComponent :
var MyComponent = React.createClass({ onHandleGiveValue: function (value) { alert(value); }, render: function () { var self = this, children = React.Children.map(this.props.children, function (c, index) { return React.addons.cloneWithProps(c, { onGiveValue: self.onHandleGiveValue.bind(self) }); }); return ( <div> {children} </div> ); } }); var MySubComponent = React.createClass({ handleClick: function() { this.props.onGiveValue(this.props.val); }, getValue: function () { return this.props.val; }, render: function () { return ( <div onClick={ this.handleClick } >{this.props.val}</div> ); } }); React.render( <div> <MyComponent> <MySubComponent val="1" /> <MySubComponent val="2" /> <MySubComponent val="3" /> </MyComponent> </div>, document.getElementById('container') );
That way, your code can pass the current value as an event to the parent component. I created a new event from the MySubComponent class named onGiveValue . At the moment, the value from this.props.val is simply passed. But of course, it could be anything.
Wiredprairie
source share