React事件

一,react事件声明

1.react事件采用驼峰式命名

2.react事件接收一个函数声明,不是函数调用的形式

//原生
<div onclick="handleClick()"></div>
//react
<div onClick={this.handleClick}></div>

二,class组件的事件绑定this问题

1.class的方法默认不会绑定 this,如果没有绑定 this.handleClickthis 并把它传入了 onClick,当你调用这个函数的时候 this 的值为 undefined


class A extends React.Component{
	constructor(props){
		super(props)	
	}
	handleClick(){
		//class的方法默认不会绑定 `this`,this的指向根据调用的方式判断
		//没有绑定调用的话this为undefined
		this.setState({a:1})
	}
	render(){
		return (
		<div onClick={this.handleClick}></div>
		)
	}
}

2.this问题的解决方式有三种

(1)constructor里使用bind为方法绑定this

class A extends React.Component{
	constructor(props){
		super(props)
		this.handleClick= this.handleClick.bind(this);	
	}
	handleClick(){
		this.setState({a:1})
	}
}

(2)在元素上绑定事件时使用箭头函数


class A extends React.Component{
	constructor(props){
		super(props)	
	}
	handleClick(){
		//class的方法默认不会绑定 `this`,this的指向根据调用的方式判断
		//没有绑定调用的话this为undefined
		this.setState({a:1})
	}
	render(){
		//render里的this指向自身
		return (
		<div onClick={()=> this.handleClick() }></div>
		)
	}
}

(3)使用箭头函数声明方法


class A extends React.Component{
	constructor(props){
		super(props)	
	}
	handleClick=()=>{
		//箭头函数的this由父作用域的this判断
		this.setState({a:1})
	}
	render(){
		//render里的this指向自身
		return (
		<div onClick={this.handleClick}></div>
		)
	}
}

三,react事件传递参数

1.要在绑定事件的位置给事件传参有两种方式,

(1)通过bind,使用bind会隐式传入事件对象e,作为函数的最后一个参数。

<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

(2)通过箭头函数,使用箭头函数需要主动传入事件对象e

<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值