React小案例: 点击按钮,数字加1

545 阅读1分钟

大家好,我是梅巴哥er,本次案例较为简单,但是有个核心思想,就是要拿到数字这个值,要想到用e.target.value
代码如下:

import React, { Component } from 'react'

export default class App extends Component {
    constructor(props) {
        super(props)
        this.state = {
            num: 1
        }
    }
    

    handleClick=(e) => {
        console.log(e.target.value)
        this.setState({
            num: e.target.value
        })
    }
    render() {
        const val = this.state.num
        return (
            <div>
                <h3>{ val }</h3>
                <button 
                value={ Number(val) + 1 }
                onClick={ this.handleClick } >点击增加</button>
            </div>
        )
    }
}