1. Trang chủ
  2. » Công Nghệ Thông Tin

Hướng dẫn ReactJS ReactJS tutorial (p9) Bài 9: ReactJS Tìm hiểu Events trong React

4 170 4

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 4
Dung lượng 82,73 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

trong React 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.

Trang 1

Bài 9: ReactJS - Tìm hiểu Events trong React

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

App.js

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>

Trang 2

<button onClick ={this.updateState}>CLICK</button>

<h4>{this.state.data}</h4>

</div>

);

}

}

export default App;

Index.js

import React from 'react';

import ReactDOM from 'react-dom';

import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('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:

App.js

import React from 'react';

Trang 3

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>

Trang 4

</div>

);

}

}

export default App;

Index.js

import React from 'react';

import ReactDOM from 'react-dom';

import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('app')); Kết quả ta được:

Ngày đăng: 03/04/2018, 17:31

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w