class Parent extends React.Component {
constructor(props) {
super(props)
// Bind the this context to the handler function
this.handler = this.handler.bind(this);
// Set some state
this.state = {
messageShown: false
};
}
// This method will be sent to the child component
handler(id) {
this.setState({
messageShown: true,
id: id
});
}
// Render the child component and set the action property with the handler as value
render() {
console.log(this.state);
return (
<div>
<Child action={this.handler} />
<div>{this.state.id}</div>
</div>
);
}
}
class Child extends React.Component {
render() {
return (
<div>
{/* The button will execute the handler function set by the parent component */}
<button onClick={() => this.props.action(1)} > button </button>
</div>
)
}
}
ReactDOM.render(<Parent />, document.getElementById('main'));