Tải bản đầy đủ (.docx) (4 trang)

Hướng dẫn ReactJS ReactJS tutorial (p8) Bài 8: ReactJs Tạo Forms trong React

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (78.17 KB, 4 trang )

Bài 8: ReactJs - Tạo Forms trong
React
Trong bài này, chúng ta sẽ tìm hiểu cách tạo form để nhập dữ liệu trong React.

Simple Example
Trong ví dụ sau đây chúng ta sẽ khởi tạo 1 input form với value= {this.state.data}, dữ
liệu trong form là state của component. Và chúng ta sẽ update state khi chúng ta thay
đổi value trong input. Chúng ta sẽ sử dụng sự kiện onChange đê kiểm tra sự thay đổi
trong input và update lại state, không dong dài nữa chúng ta cùng xem ví dụ để hiểu rõ
hơn nào.
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(e) {
this.setState({data: e.target.value});
}


render() {
return (
<div>


onChange = {this.updateState} />

{this.state.data}


</div>
);
}
}
export default App;

Biến e trong updateState là 1 synthetic event, hiên tại các bạn chưa cần quan tâm đến
nó đâu, mình sẽ nói rõ hơn về nó trong series React nâng cao.
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('app'));

Khi chạy chương trình các bạn sẽ được kết quả như sau:

Khi các bạn thay đổi giá trị trong input thì giá trị thẻ h4 cũng thay đổi theo. (update
state-> render()).


Complex Example
Trong ví dụ này, chúng ta sẽ sử dụng form ở ví dụ trên như 1 component và là con của
component App. Chúng ta sẽ chuyển state:data cùng với onChange event xuống cho
form thông qua props( các bạn xem bài này nếu chưa biết về props, hiểu được props
sẽ dễ hiểu ví dụ này). Các bạn xem kĩ ví dụ này, bài sau sẽ lại đề cập đến nó đấy.
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(e) {
this.setState({data: e.target.value});
}
render() {
return (
<div>
updateStateProp = {this.updateState}></Content>
</div>
);


}
}
class Content extends React.Component {
render() {
return (
<div>

onChange = {this.props.updateStateProp} />

{this.props.myDataProp}


</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ả:

End bài 8 tại đây, các bạn xem lại rồi thực hành biến tấu nhiều thêm để hiểu rõ hơn
nha. Nếu có thắc mắc gì bạn cứ comment bên dưới mình sẽ giải đáp trong vòng 24h.



×