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.
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)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
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> </> ); }
\
: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') )
:
add brackets:
##onClick={ this.fn( ) }
3. Event processing-this points to the problem
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.
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 undefined
3. Solving the event function this points to:
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 bindclass 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: 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:
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 data-id="heading-17"><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' } })
setState
进行修改。由state的值来控制表单元素的值
示例代码:
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( { 要修改的部分数据 } )
操作对应的状态即可
示例代码:
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!