更新 state

2019-02-27  本文已影响0人  SingleDiego

在 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。

上一篇 下一篇

猜你喜欢

热点阅读