react为按钮绑定点击事件和修改属性值

时间:2023-03-09 08:31:29
react为按钮绑定点击事件和修改属性值

注意点:1、事件名称由react提供,所以事件名首字母大写。比如onClick,onMouseOver。

2、为事件提供的处理函数,格式必须是onClick={function},没有小括号。

3、绑定事件的格式写法为:

<button onClick={()=>this.show('传的参数1','传的参数2')}>按钮</button>

show=(arg1,arg2)=>{

console.log('方法传的参数为'+arg1+arg2)

}

import React,{component} from 'react';

class test extends component{
    constructor(){
        super()
        //msg是实例属性
        this.state={
            msg:"哈哈",
        }
    }
    render(){
        return <div>
            <button onClick={()=>this.show('1','2')}>按钮</button>
            <h3>{this.state.msg}</h3>
        </div>
    }
    show=(arg1,arg2)=>{
        // console.log('show方法已经被调用'+arg1+arg2)
        this.setState({
            msg:"重新赋值!必须使用setState这个方法。"
        })
    }

}