React添加事件

React添加事件,和DOM上添加事件类似,但又有细微的不同. React添加事件,需要注意: 1.React的事件命名采用小驼峰(camelCase)的命名方式,DOM采用的是纯小写的方式; 2.使用JSX语法时,需要传入一...

React添加事件,和DOM上添加事件类似,但又有细微的不同.

React添加事件,需要注意:

1.React的事件命名采用小驼峰(camelCase)的命名方式,DOM采用的是纯小写的方式;

2.使用JSX语法时,需要传入一个函数作为事件的处理函数,DOM传入的是一个字符串(虽然DOM中传入的事件名称也可以是函数名称,但数据类型还是一个字符串)

DOM元素添加事件

<a href="#" onclick="testClick();">点击我</a>

React中添加事件

<button onClick={this.testClick}>点击我</button>

React中不能通过返回false来阻止元素的默认行为,只能通过显示的设置preventDefault()来阻止默认的行为,而DOM中阻止元素默认行为的方式有两种:一种是内联脚本直接返回false,另外一种是事件处理函数中显示调用preventDefault方法.

DOM中阻止默认行为的方式:

<a href="http://www.baidu.com" onclick="return false;">点击我</a>
这种内联到HTML中的方式,可以通过直接返回false的方式阻止a元素默认行为跳转,也可以通过在响应事件中显示调用preventDefault方法.如:
<!--注意传入的参数需要是固定的event,不能修改为其他的值-->
<a href="http://www.baidu.com" onclick="testClick(event);">点击我</a>
<script>
    function testClick(e) {
        console.log("处理一些其他事情");
        e.preventDefault();
    }
</script>

React中阻止元素默认行为的方法:

testClick(e){
    console.log("处理些其他事情");
    e.preventDefault();
}
<a href="http://www.baidu.com" onClick={this.testClick}>点击我</a>

事件处理函数中不需要传入任何参数.

React中元素绑定事件

主要有个this的指向问题,在以类的继承方式定义的组件中,事件处理函数中的this并不是指向当前的组件.如果我们直接在React元素中使用this就会报异常,因为this并不是指向该组件.那么我们就需要手动的将this指向到当前组件,才可以使用this,将this绑定到当前组件常用的方法有4中:

1.通过箭头函数

<a href="http://www.mop.com" onClick={(e) => this.testClick(e)}>点击我</a>

2.将事件处理函数使用箭头函数的方法来写

testClick = (e) => {
    console.log("处理点事情");
    e.preventDefault();
}
<a href="http://www.baidu.com" onClick={this.testClick}>点击我吧</a>

3.在调用的地方绑定通过bind绑定;

<a href="http://www.baidu.com" onClick={this.handleClickEvent.bind(this)}>点击我</a>

4.在构造函数constructor中提前绑定;

    constructor(props) {
        super(props);
        this.state = {
            name: this.props.name,
            date: new Date(),
            id: this.props.id
        };
        this.handleClickEvent = this.handleClickEvent.bind(this);
    }

<a href="http://www.baidu.com" onClick={this.handleClickEvent}>点击我吧</a>

向事件处理函数传递参数

很多操作中,我们都需要向事件的处理函数传递参数,如在删除或标记一条数据的时候,需要把当前数据的ID传递给事件处理函数,让它知道去处理哪条数据.

常用的传递数值的方式有两种:

1.箭头函数的方式

delUser(id, e){
    console.log(id);
}
<a href="http://www.baidu.com" onClick={(e) => this.delUser(this.state.id, e)}>删除</a>

2.通过bind向监听函数传参,需要注意在类组件中定义的监听函数,事件对象e要在传递参数的后面

delUser(id, e){
    console.log(id);
}
<a href="http://www.baidu.com" onClick={this.delUser.bind(this, this.state.id)}>删除</a>

其实无论是使用箭头函数,还是通过bind绑定监听事件的方式传参,事件响应函数中事件对象e,在参数列表中都是排在最后.

goRenren(id,name, e){
    console.log(id);
    console.log(name);
}
<button onClick={(e) => this.goRenren(this.state.id,this.state.name, e)}>删除</button>
  • 发表于 2020-04-14 22:27
  • 阅读 ( 122 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除