Trong bài này chúng ta sẽ cùng tìm hiểu cách xử lý các events trong React.
Simple Example¶
Trong ví dụ này chúng ta sẽ sử dụng một component cùng với onClick event dùng để update state khi ta click vào button.
...
Code Block | ||
---|---|---|
| ||
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; |
Kết quả ta được:
...
Child Events¶
Khi chúng ta muốn update state của component cha từ component con, ta tạo 1 event handler(updateState) ở component cha và chuyền nó xuống component con thông qua prop (updateStateProp). Các bạn xem ví dụ sau:
...