English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this chapter, we will learn how to use events.
This is a simple example where we will use only one component. We just addedonClick
event,updateState
Once the button is clicked, the event will trigger the function.
import React from 'react'; class App extends React.Component { constructor(props) { super(props); this.state = { data: 'Initial data...' } this.updateState = this.updateState.bind(this); }; updateState() { this.setState({data: 'Data updated...'}) } render() { return ( <div> <button onClick={this.updateState}>CLICK</button> <h4>{this.state.data}</h4> </div> ); } } export default App;
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(<App/, document.getElementById('app'));
This will produce the following result.
When we needstate
When updating the parent component from its child, you can create an event handler in the parent component (updateState
), and use it as a prop (updateStateProp
Pass it to child components, where we can call it.
import React from 'react'; class App extends React.Component { constructor(props) { super(props); this.state = { data: 'Initial data...' } this.updateState = this.updateState.bind(this); }; updateState() { this.setState({data: 'Data updated from the child component...'}) } render() { return ( <div> <Content myDataProp = {this.state.data} updateStateProp = {this.updateState}</Content> </div> ); } } class Content extends React.Component { render() { return ( <div> <button onClick = {this.props.updateStateProp}>CLICK</button> <h3>{this.props.myDataProp}</h3> </div> ); } } export default App;
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(<App/, document.getElementById('app'));
This will produce the following result.