state là gì

React State là gì? Code ví dụ React state.

React State là gì?

Bạn đang xem: state là gì

Trong React, state là những bộ phận nhằm xây hình thành một component.

State là lưu tàng trữ những độ quý hiếm của component, khi state thay cho thay đổi thì component cũng khá được render lại.

Tạo State object

Đối tượng state được tạo ra nhập hàm constructor (hàm khởi tạo) của component.

state rất có thể đựng nhiều những tính chất không giống nhau:

Ví dụ:

class Name extends React.Component { constructor(props) { super(props); this.state = { firstName: "kai", lastName: "tran" }; } render() { return ( <div> <p>Hello: {this.state.firstName} {this.state.lastName}</p> </div> ); } }

Code ví dụ React state, thay cho thay đổi state

Trong ví dụ này bản thân tiếp tục triển khai dùng component <Name /> để render, tiếp sau đó thay cho thay đổi state nhằm browser render lại component <Name />

Tạo tệp tin index.html

<html> <head> <title>stackjava: ReactJS Tutorial!</title> <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script> <script src="https://unpkg.com/[email protected]/babel.min.js"></script> </head> <body> <div id='root'></div> <script src="index.jsx" type="text/babel"></script> </body> </html>

Tạo tệp tin index.jsx

Để thay cho thay đổi state, tớ sử dụng hàm setState() chứ ko được gán thẳng độ quý hiếm cho những tính chất nhập state.

Xem thêm: vegetable đọc tiếng anh là gì

Fucntion changeName() tiếp tục triển khai thay cho thay đổi state

Khi click vào  button, nó sẽ bị gọi cho tới function changeName() thực hiện mang đến state bị thay cho thay đổi và component sẽ tiến hành render lại

class Name extends React.Component { constructor(props) { super(props); this.state = { firstName: "kai", lastName: "tran" }; } changeName = () => { this.setState({firstName: "sena"}); this.setState({lastName: "nguyen"}); } render() { return ( <div> <p>Hello: {this.state.firstName} {this.state.lastName}</p> <br/> <button type="button" onClick={this.changeName}>change name</button> </div> ); } } const rootElement = document.getElementById('root') ReactDOM.render( <Name />, rootElement )

Demo:

Chạy tệp tin index.htmlindex.jsx bên trên server http: (Xem lại: ví dụ react hello world)

React State là gì? Code ví dụ React state

 

Okay, Done!

References:

https://reactjs.org/docs/state-and-lifecycle.html

Xem thêm: sick là gì