ReactJS开发笔记

2-useState

2020-02-02  本文已影响0人  钢笔先生

Time: 20200126

函数组件中使用状态。

类组件写法

import React, { Component } from 'react'

class ClassCounter extends Component {
    // rconst 快捷键生成构造函数
    constructor(props) {
        super(props)
    
        this.state = {
            count: 0, 
        }
    }
    incrementCount = () => {
        this.setState({
            count: this.state.count + 1
        })
    }
    render() {
        return (
            <div>
               <button onClick={this.incrementCount}> Count {this.state.count}</button> 
            </div>
        )
    }
}

export default ClassCounter

注意类组件的用法。

函数式组件写法

import React, {useState} from 'react'

// RFCE生成函数组件
function HookCounter() {
    const [count, setCount] = useState(0)
    return (
        <div>
            <button onClick={() => setCount(count + 1)}> Count {count}</button>
        </div>
    )
}

export default HookCounter

在事件调用中,因为是函数调用,所以用的是箭头函数。

useState的用法很简单,useState(初始值),然后返回一个变量和一个控制此变量的函数。

底层机制后面可以看看,先用起来。

关于Hooks的规则

截屏2020-01-26下午5.57.26.png

END.

上一篇 下一篇

猜你喜欢

热点阅读