React教程

React 状态

状态是可更新的结构,用于包含有关组件的数据或信息。组件中的状态可以随时间变化。状态随时间的变化可以作为对用户操作或系统事件的响应而发生。具有状态的组件称为有状态组件。这是React组件的核心,它决定了该组件的行为及其呈现方式。它们还负责使组件动态和交互式。
状态必须保持尽可能简单。可以使用 setState()方法进行设置,并调用setState()方法触发UI更新。状态代表组件的本地状态或信息。它只能在组件内部或由组件直接访问或修改。要在发生任何交互之前设置初始状态,我们需要使用 getInitialState()方法。
例如,如果我们有五个组成部分需要状态中的数据或信息,那么我们需要创建一个容器组件,以保持所有状态。

定义状态

要定义一个状态状态,您必须首先声明一组默认值以定义组件的初始状态。为此,添加一个类构造函数,该构造函数使用this.state分配初始状态。可以在 render()方法中呈现" this.state "属性。

示例

以下示例代码显示了如何使用ES6语法创建有状态组件。
import React, { Component } from 'react';
class App extends React.Component {
 constructor() {
      super();    
      this.state = { displayBio: true };
      }
      render() {
          const bio = this.state.displayBio ? (
              <div>
                  <p><h3>lidihuo is one of the best Java training institute in Noida, Delhi, Gurugram, Ghaziabad and Faridabad. We have a team of experienced Java developers and trainers from multinational companies to teach our campus students.</h3></p> 
          </div>
              ) : null;
              return (
                  <div>
                      <h1> Welcome to lidihuo!! </h1>
                      { bio } 
                  </div>
              );
     }
}
export default App;
要设置状态,需要在构造函数中调用super()方法。这是因为在调用super()方法之前未初始化this.state。

更改状态

我们可以使用setState()方法并将新的状态对象作为论据。现在,在上面的示例中创建一个新方法toggleDisplayBio()并将该关键字绑定到toggleDisplayBio()方法,否则我们将无法在toggleDisplayBio()方法内部访问此方法。
this.toggleDisplayBio = this.toggleDisplayBio.bind(this);

示例

在此示例中,我们将向 render ()方法添加按钮。单击此按钮将触发toggleDisplayBio()方法,该方法显示所需的输出。
import React, { Component } from 'react';
class App extends React.Component {
 constructor() {
      super();    
      this.state = { displayBio: false };
      console.log('Component this', this);
      this.toggleDisplayBio = this.toggleDisplayBio.bind(this);
      }
      toggleDisplayBio(){
          this.setState({displayBio: !this.state.displayBio});
          }
      render() {
          return (
              <div>
                  <h1>Welcome to lidihuo!!</h1>
                  {
                      this.state.displayBio ? ( 
                          <div>
                              <p><h4>lidihuo is one of the best Java training institute in Noida, Delhi, Gurugram, Ghaziabad and Faridabad. We have a team of experienced Java developers and trainers from multinational companies to teach our campus students.</h4></p>
                              <button onClick={this.toggleDisplayBio}> Show Less </button>
                      </div>
                          ) : (
                              <div>
                                  <button onClick={this.toggleDisplayBio}> Read More </button>
                              </div>
                        )
                  }
             </div>
      )
    }
}
export default App;

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4