在本章中,我们将学习如何使用事件.
这是一个简单的例子,我们只使用一个零件.我们只是添加 onClick 事件,一旦点击该按钮就会触发 updateState 功能.
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'));
这将产生以下结果.
当我们需要更新父母的状态时来自其子组件的组件,我们可以在父组件中创建一个事件处理程序( updateState ),并将其作为prop( updateStateProp )传递给我们可以调用的子组件它.
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'));
这将产生以下结果.