State,翻译为“状态”,实际指的就是组件中的数据。React 中给类组件提供了一个 state 属性用来管理组件内部的私有数据 (状态)。
在 React 16.8 版本之前,函数式组件也称为”无状态组件”,也就是说在函数式组件内部无法去定义组件的状态。所以暂时我们只针对类定义组件来学习 State 的使用。
定义 state 数据
类组件中的 state,是将其作为了组件实例对象的一个属性在 constructor 中去进行初始化。
import React, { Component } from 'react'
export default class ClassState extends Component {
constructor() {
super();
this.state = {
count: 0
}
}
render() {
// ...
}
}
根据 class 中实例属性的新写法,我们也可以用以下方式实现 state 的初始化:
import React, { Component } from 'react'
export default class ClassState extends Component {
state = {
count: 0
}
render() {
// ...
}
}
更推荐使用第二种方式。
访问 state 数据
在类组件中,通过 this.state 来访问 state 中的数据,从而实现 state 数据的渲染:
import React, { Component } from 'react'
export default class ClassState extends Component {
state = {
count: 0
}
render() {
return (
<>
<h1>计数器:{this.state.count}</h1>
</>
)
}
}
当访问的数据较多时,我们也可以在 render() 方法顶部先对 state 中的数据做一个解构:
import React, { Component } from 'react'
export default class ClassState extends Component {
state = {
count: 0
}
render() {
const { count } = this.state;
return (
<>
<h1>计数器:{count}</h1>
</>
)
}
}
修改 state 数据
React 提供了一个 setState 方法用于更新 State。语法结构如下:
this.setState({
数据名: 新数据值
})
示例代码如下:
export default class ClassState extends Component {
state = {
count: 0
}
increment = () => {
this.setState({
count: this.state.count + 1
})
}
render() {
const { count } = this.state;
return (
<>
<h1>计数器:{count}</h1>
<button onClick={() => {
this.setState({
count: count - 1
})
}}>-1</button>
<button onClick={this.increment}>+1</button>
</>
)
}
}
获取节点(扩展)
在某些情况下,我们也需要在 React 中获取节点对象。
React 中提供了一个 createRef() 方法用来创建一个 React 元素的引用,通过 ref 属性将该引用保存到 React 元素身上:
import { Component, createRef } from 'react'
export default class ClassState extends Component {
render() {
const inputRef = createRef();
return (
<input type="text" ref={inputRef} />
)
}
}
ref 绑定成功后,就可以通过 inputRef.current 获取到当前 React 元素节点。
上例中输入框的值也可以通过这种方式获取了:
import { Component, createRef } from 'react'
export default class ClassState extends Component {
render() {
const inputRef = createRef();
return (
<input type="text" ref={inputRef} onBlur={() => {
console.log(inputRef.current.value);
}}/>
)
}
}