美文网首页
更新 state

更新 state

作者: SingleDiego | 来源:发表于2019-02-27 11:07 被阅读0次

在 React 中我们并不直接修改 state 里面的值,而是应该使用 setState() 方法,这样才会让 React 知道 state 被修改,从而更新渲染 DOM。

import React, { Component } from 'react';

class Counter extends Component{
    state = {
        count: 1,
    };

    handleClick = () => {
        this.setState({count: this.state.count + 1})
    };

    render() {
        return(
            <div>
                <p>{ this.state.count }</p>
                <button onClick={ this.handleClick }>Click</button>
            </div>
            ); 
    };
}

以上代码点击按钮后会给 count +1 然后在渲染出来。




传递参数

上面的 handleClick() 方法并未带上参数,如果我们想带参数,较方面的方法是调用时使用箭头函数:

import React, { Component } from 'react';

class Counter extends Component{
    state = {
        count: 0,
    };

    handleClick = num => {
        this.setState({count: this.state.count + num});
    };

    render() {
        const num = 10; // 设定参数
        return(
            <div>
                <p>{ this.state.count }</p>
                <button onClick={ () => this.handleClick(num) }>Click</button>
            </div>
            ); 
    };
}

现在点击按钮后,会给 count 加上 10。

相关文章

网友评论

      本文标题:更新 state

      本文链接:https://www.haomeiwen.com/subject/rhuxuqtx.html