1.直接绑定
事件名必须时小驼峰式的,语法:
<button onClick={function(){console.log('a')}}>按钮</button>
2.
语法:
export default class BindEvent extends React.Component{
constructor(){
super();
this.state={}
}
render(){
return <div>
<button onClick={this.hello}>按钮</button>
</div>
}
hello(){
console.log('niddnhao')
}
}
3.绑定多个事件
export default class BindEvent extends React.Component{
constructor(){
super();
this.state={}
}
render(){
return <div>
<button onClick={()=>{this.hello(1); this.world(2)}}>按钮</button>
</div>
}
hello(a){
console.log(a)
}
world(a){
console.log(a + '----')
}
}
绑定事件实现数据实时更新
- React中用this.setState({})更改数据并更新
export default class BindEvent extends React.Component{
constructor(){
super();
this.state={
msg:'haha'
}
}
render(){
return <div>
<button onClick={(e) => { this.hello();}}>按钮</button>
{this.state.msg}
</div>
}
hello(){
this.setState({msg :this.state.msg +=1})
}
}
- this.setState({})方法执行时异步的,如果要获取到最新的值,需要使用this.setState({},callback函数)
hello(){
this.setState({
msg :this.state.msg+=1
},()=>{
console.log(this.state.msg)
})
}
- 可以使用//#region和//#endregion将这两者之间的代码折叠起来
双向数据绑定
- 方式一
onchange
事件
<input type="text" style={{width:"100%"}} value={this.state.msg} onChange={(e)=>{this.textChange(e)}}/>
textChange(e){
this.setState({
msg: e.target.value
})
}
- 方式二
ref
属性
<input type="text" ref="text" value={this.state.msg}} onChange={()=>{ textChange()}/>
textChange(){
this.setState({
msg: this.refs.text.value
})
}