How to change component state in react

青灯夜游
Release: 2022-12-15 19:19:24
Original
2834 people have browsed it

In react, you can use setState() to modify the state of the component. setState() is a method used to update the component state. This method can queue changes to the component state and also obtain the latest state. The syntax is "this.setState({part of the data to be modified })".

How to change component state in react

#The operating environment of this tutorial: Windows7 system, react18 version, Dell G3 computer.

1. Stateful components and stateless components


1. First understand what state is:

Definition:

is data used to describe the shape of things at a certain moment, generally called state. (It can be simply understood that the state is data)For example: the inventory quantity of books on September 23; the height of a person at the age of 18. There are also related concepts in vue

Features:

can be changed. After the change, the view will have corresponding changes (two-way data binding)

2. Stateful components and stateless components

Stateful components: components that can define state.

Class component is a stateful component.

Stateless components: components that cannot define state.

Function component is also called stateless component

Note:

On February 6, 2019, in React 16.8 version React Hooks are introduced so that functional components can also define their own state. [Related recommendations:

Redis video tutorial, Programming teaching]

This article mainly explains the status of

class components

3. The state of class components

1) Define the state

Use

state = { } for initialization

import React from "react";

export default class Hello extends React.Component {

  // 这里的state就是状态
  state = {
    list:  [{ id: 1, name: "给我一个div" }],
    isLoading : true
  };
}
Copy after login

2) Use

 render() {
    return (
      <>
            <h1>姓名-{this.state.name}</h1>
            <ul>
            {this.state.list.map((item) => (
            <li key={item.id}>{item.name}</li>
             ))}
            </ul>
        <div>{this.state.isLoading ? "正在加载" : "加载完成"}</div>
      </>
    );
  }
Copy after login

in the view 2. Event binding


1. Format

##

\

Note

:React event names use camel case naming, such as: onMouseEnter, onFocus, onClick...

2. Example

import React from &#39;react&#39;
import ReactDOM from &#39;react-dom&#39;

const title = <h1>react中的事件</h1>


export default class Hello extends React.Component {
  fn() {
    console.log(&#39;mouseEnter事件&#39;)
  }
  render() {
    return (
      <div
            onClick = { () => console.log(&#39;click事件&#39;) }
            onMouseEnte r = { this.fn }
      </div>
    )
  }
}

const content = (
  <div>
    {title}
    {<Hello />}
  </div>
)

ReactDOM.render ( content , document.getElementById (&#39;root&#39;) )
Copy after login

Note

:

    The event name is in camel case naming format
  • Add methods in the class
  • this . fn
  • Don’t

    add brackets:

    ##onClick={ this.fn( ) }
      At this time, fn() will be called first, and then the execution result of fn will be used as the processing function of the click event
    Don’t forget to write this

3. Event processing-this points to the problem

1. Problem code:

class App extends React.Component {
        // 组件状态
      state = {
        msg: &#39;hello react&#39;
      }
      
      // 事件处理函数
      handleClick() {
            console.log(this) // 这里的this是 undefined
      }
      
      render() {
            console.log(this) // 这里的this是当前的组件实例 App
        
          return (
              <div>
                    <button onClick={this.handleClick}>点我</button>
              </div>
        )
      }
}
Copy after login
The result is this:

This in the render method points to the current react component.

    This in the event handler points to
  • undefined
  • 2. Reason:

class

The internals of classes and modules are in strict mode by default, so there is no need to use

use strict to specify the running mode. As long as your code is written in a class or module, only strict mode is available, so the function this in the class points to undefined3. Solving the event function this points to:

Method 1:

Wrap an arrow function in the event handler

Disadvantage: An additional arrow needs to be wrapped outside the handler function Function, the structure is not beautiful

Advantages:

As mentioned before, don’t add parentheses when calling the processing function in

{this.handleClick ()}

, otherwise The program will be executed immediately. Now after wrapping an arrow function outside, you can not only add parentheses, but also pass parameters.

class App extends React.Component {
  state = {
    msg: &#39;hello react&#39;
  }

  handleClick () {
    console.log(this.state.msg)
  }

  render () {
    return (
      <div>
        <button onClick={ () => { this.handleClick ( ) }}>点我</button>
      </div>
    )
  }
}
Copy after login
Method 2: Use bind

Change the function this pointer through the bind() method and do not execute the function's characteristic solution

class App extends React.Component {
  state = {
    msg: &#39;hello react&#39;
  }

  handleClick () {
    console.log(this.state.msg)
  }

  render () {
    return (
      <div>
        <button onClick={ this.handleClick.bind (this) }>点我</button>
      </div>
    )
  }
}
Copy after login
Method 3:

Use the arrow function directly when declaring the event processing function in the class

class App extends React.Component {
  state = {
    msg: &#39;hello react&#39;
  }

  handleClick = () => {
    console.log(this.state.msg)
  }
  render() {
    return (
      <div>
        <button onClick={this.handleClick}>点我</button>
      </div>
    )
  }
}
Copy after login
Advantages:

The code is concise, intuitive, and the most used method

4. Modify the status of the component

##Note:


cannot pass Directly modify the value in the state to change the view! ! !

Modify through the
this.setState()

method


In react, setstate is a method used to update the component state state ;setState() queues changes to the component state and notifies React that it needs to re-render this component and its subcomponents with the updated state. <h3 data-id="heading-17"><strong>1.语法:</strong></h3><p><code>语法:this.setState( { 要修改的部分数据 } )
这是继承自React.Component的修改类组件状态的方法

state = {
    count: 0,
    list: [1, 2, 3],
    person: {
      name: &#39;jack&#39;,
      age: 18
    }
  }
  
  // 【不推荐】直接修改当前值的操作:
  this.state.count++
  ++this.state.count
  this.state.count += 1
  this.state.count = 1
  this.state.list.push(4)
  this.state.person.name = &#39;rose&#39;
  
  // 【推荐】不是直接修改当前值,而是创建新值的操作:
  this.setState({
    count: this.state.count + 1,
    list: [...this.state.list, 4],
    person: {
      ...this.state.person,
    	// 要修改的属性,会覆盖原来的属性,这样,就可以达到修改对象中属性的目的了  
      name: &#39;rose&#39;
    }
  })
Copy after login

五、表单处理-受控组件


  • HTML中表单元素是可输入的,即表单维护着自己的可变状态(value)。
  • 但是在react中,可变状态通常是保存在state中的,并且要求状态只能通过setState进行修改。
  • React中将state中的数据与表单元素的value值绑定到了一起,由state的值来控制表单元素的值
  • 受控组件:value值受到了react控制的表单元素

示例代码:

class App extends React.Component {
  state = {
    msg: &#39;hello react&#39;
  }

  handleChange = (e) => {
    this.setState({
      msg: e.target.value
    })
  }

   // value 绑定state 配合onChange事件双向绑定
  render() {
    return (
      <div>
        <input type="text" value={this.state.msg} onChange={this.handleChange}/>
      </div>
    )
  }
}
Copy after login

注意事项

使用受控组件的方式处理表单元素后,状态的值就是表单元素的值。即:想要操作表单元素的值,只需要通过this.setState( { 要修改的部分数据 } )操作对应的状态即可

六、表单处理-非受控组件-ref


  • 受控组件是通过 React 组件的状态来控制表单元素的值
  • 非受控组件是通过手动操作 DOM 的方式来控制
  • ref:用来在 React 中获取 DOM 元素

示例代码:

import { createRef } from &#39;react&#39;

class Hello extends Component {
  txtRef = createRef()

  handleClick = () => {
    // 文本框对应的 DOM 元素
    // console.log(this.txtRef.current)

    // 文本框的值:
    console.log(this.txtRef.current.value)
  }

  render() {
    return (
      <div>
        <input ref={this.txtRef} />
        <button onClick={handleClick}>获取文本框的值</button>
      </div>
    )
  }
}
Copy after login

(学习视频分享:编程基础视频

The above is the detailed content of How to change component state in react. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template