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

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

React State là gì?

Trong React, state là các thành phần để xây dựng nên một component.

State là lưu lưu trữ các giá trị của component, khi state thay đổi thì component cũng được render lại.

Tạo State object

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

state có thể chứa nhiều các thuộc tính khác 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 đổi state

Trong ví dụ này mình sẽ thực hiện sử dụng component <Name /> để render, sau đó thay đổi state để browser render lại component <Name />

Tạo file 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/babel-standalone@6.26.0/babel.min.js"></script>
</head>
<body>
  <div id='root'></div>
  <script src="index.jsx" type="text/babel"></script>

</body>
</html>

Tạo file index.jsx

Để thay đổi state, ta dùng hàm setState() chứ không được gán trực tiếp giá trị cho các thuộc tính trong state.

Fucntion changeName() sẽ thực hiện thay đổi state

Khi click vào  button, nó sẽ gọi tới function changeName() làm cho state bị thay đổi và component sẽ được 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 file index.htmlindex.jsx 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

stackjava.com