How to change component state in react
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 })".
#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 ofclass components
3. The state of class components
1) Define the state
Usestate = { } for initialization
import React from "react"; export default class Hello extends React.Component { // 这里的state就是状态 state = { list: [{ id: 1, name: "给我一个div" }], isLoading : true }; }
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> </> ); }
in the view 2. Event binding
1. Format
##\
:React event names use camel case naming, such as: onMouseEnter, onFocus, onClick...
2. Exampleimport React from 'react'
import ReactDOM from 'react-dom'
const title = <h1>react中的事件</h1>
export default class Hello extends React.Component {
fn() {
console.log('mouseEnter事件')
}
render() {
return (
<div
onClick = { () => console.log('click事件') }
onMouseEnte r = { this.fn }
</div>
)
}
}
const content = (
<div>
{title}
{<Hello />}
</div>
)
ReactDOM.render ( content , document.getElementById ('root') )
Copy after login
Noteimport React from 'react' import ReactDOM from 'react-dom' const title = <h1>react中的事件</h1> export default class Hello extends React.Component { fn() { console.log('mouseEnter事件') } render() { return ( <div onClick = { () => console.log('click事件') } onMouseEnte r = { this.fn } </div> ) } } const content = ( <div> {title} {<Hello />} </div> ) ReactDOM.render ( content , document.getElementById ('root') )
:
- 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
3. Event processing-this points to the problem
1. Problem code:
class App extends React.Component {
// 组件状态
state = {
msg: 'hello react'
}
// 事件处理函数
handleClick() {
console.log(this) // 这里的this是 undefined
}
render() {
console.log(this) // 这里的this是当前的组件实例 App
return (
<div>
<button onClick={this.handleClick}>点我</button>
</div>
)
}
}
Copy after loginThe result is this:
class App extends React.Component { // 组件状态 state = { msg: 'hello react' } // 事件处理函数 handleClick() { console.log(this) // 这里的this是 undefined } render() { console.log(this) // 这里的this是当前的组件实例 App return ( <div> <button onClick={this.handleClick}>点我</button> </div> ) } }
This in the render method points to the current react component.
- This in the event handler points to
- undefined
class
The internals of classes and modules are in strict mode by default, so there is no need to useuse 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 undefined
3. 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
{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: 'hello react' } handleClick () { console.log(this.state.msg) } render () { return ( <div> <button onClick={ () => { this.handleClick ( ) }}>点我</button> </div> ) } }
Method 2: Use bindChange the function this pointer through the bind() method and do not execute the function's characteristic solution
class App extends React.Component { state = { msg: 'hello react' } handleClick () { console.log(this.state.msg) } render () { return ( <div> <button onClick={ this.handleClick.bind (this) }>点我</button> </div> ) } }
Method 3: Use the arrow function directly when declaring the event processing function in the class
class App extends React.Component { state = { msg: 'hello react' } handleClick = () => { console.log(this.state.msg) } render() { return ( <div> <button onClick={this.handleClick}>点我</button> </div> ) } }
Advantages:
The code is concise, intuitive, and the most used method4. 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()
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 id="strong-语法-strong"><strong>1.语法:</strong></h3><p><code>语法:this.setState( { 要修改的部分数据 } )
这是继承自React.Component
的修改类组件状态的方法
state = { count: 0, list: [1, 2, 3], person: { name: 'jack', 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 = 'rose' // 【推荐】不是直接修改当前值,而是创建新值的操作: this.setState({ count: this.state.count + 1, list: [...this.state.list, 4], person: { ...this.state.person, // 要修改的属性,会覆盖原来的属性,这样,就可以达到修改对象中属性的目的了 name: 'rose' } })
五、表单处理-受控组件
- HTML中表单元素是可输入的,即表单维护着自己的可变状态(value)。
- 但是在react中,可变状态通常是保存在state中的,并且要求状态只能通过
setState
进行修改。 - React中将state中的数据与表单元素的value值绑定到了一起,
由state的值来控制表单元素的值
- 受控组件:value值受到了react控制的表单元素
示例代码:
class App extends React.Component { state = { msg: 'hello react' } 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> ) } }
注意事项:
使用受控组件的方式处理表单元素后,状态的值就是表单元素的值。即:想要操作表单元素的值,只需要通过this.setState( { 要修改的部分数据 } )
操作对应的状态即可
六、表单处理-非受控组件-ref
- 受控组件是通过 React 组件的状态来控制表单元素的值
- 非受控组件是通过手动操作 DOM 的方式来控制
- ref:用来在 React 中获取 DOM 元素
示例代码:
import { createRef } from 'react' 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> ) } }
(学习视频分享:编程基础视频)
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

Vue.js has become a very popular framework in front-end development today. As Vue.js continues to evolve, unit testing is becoming more and more important. Today we’ll explore how to write unit tests in Vue.js 3 and provide some best practices and common problems and solutions.

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

Cross-domain is a scenario often encountered in development, and it is also an issue often discussed in interviews. Mastering common cross-domain solutions and the principles behind them can not only improve our development efficiency, but also perform better in interviews.

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

At the beginning, JS only ran on the browser side. It was easy to process Unicode-encoded strings, but it was difficult to process binary and non-Unicode-encoded strings. And binary is the lowest level data format of the computer, video/audio/program/network package

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

With the development of Internet technology, front-end development has become increasingly important. Especially the popularity of mobile devices requires front-end development technology that is efficient, stable, safe and easy to maintain. As a rapidly developing programming language, Go language has been used by more and more developers. So, is it feasible to use Go language for front-end development? Next, this article will explain in detail how to use Go language for front-end development. Let’s first take a look at why Go language is used for front-end development. Many people think that Go language is a
