在本章中,我們將學(xué)習(xí)如何使用事件。
這是一個簡單的示例,其中我們將只使用一個組件。我們只是添加了onClick
事件,updateState
一旦單擊按鈕,該事件將觸發(fā)功能。
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'));
這將產(chǎn)生以下結(jié)果。
當(dāng)我們需要state
從其子級中更新父級組件時,可以在父級組件中創(chuàng)建一個事件處理程序(updateState
),并將其作為prop(updateStateProp
)傳遞給子級組件,在這里我們可以對其進(jìn)行調(diào)用。
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'));
這將產(chǎn)生以下結(jié)果。