useState是react自带的一个hook函数,它的作用是用来声明状态变量
声明的方式
const [ count , setCount ] = useState(0)
注意:这是数组的解构赋值的方式,如果不用解构赋值,则:
let _useState = useState(0) let count = _useState[0]
let setCount = _useState[1]
例子:
import React, { useState } from ‘react‘ //点击按钮,对点击次数计数
//函数组建的方法 export default function App() { const [ count , setCount ] = useState(0) return ( <div> You clicked {count} times. <button onClick={()=>{setCount(count+1)}}>click me</button> </div> ) }
同样的功能相较于函数组件,类组件则更加繁琐:需要绑定this
import React, { Component } from ‘react‘
//点击按钮,对点击次数计数 //类组件的方法 export default class App extends Component { constructor(props){ super(props) this.state = { count : 0 } } render() { return ( <div> You clicked {this.state.count} times. <button onClick={this.addCoount.bind(this)}>click me</button> </div> ) } addCoount(){ this.setState({count:this.state.count+1}) } }
原文:https://www.cnblogs.com/spikekk/p/14742040.html