You can’t call methods on child components in React. You can only set properties. (The child is actually a ReactElement
which contains information about the class and associated properties. It is not an instance of the component you created).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | var MyComponent = React.createClass({ onHandleGiveValue: function (value) { alert(value); }, render: function () { const children = React.Children.map(this.props.children, child => React.cloneElement(child, { onGiveValue: this.onHandleGiveValue.bind(this) })); 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') ); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.