React绑定事件的方法总结

React绑定事件的方法总结

在使用react进行组件化开发过程中,对组件中的某一个元素进行绑定事件是一个经常做的工作,比如:提交表单按钮click事件、文本框输入值后的onchange事件等等。以下总结下我在平常开发中常用的4种方法。

1、在元素中写bind

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import React from 'react';
export default class Component extends React.Component {
constructor(props){
super(props)
}
onClick(e){
console.log(e)
}
render(){
return (
<button onClick = {this.onClick.bind(this)} />
)
}
}

2、在constructor中写bind

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import React from 'react';
export default class Component extends React.Component {
constructor(props){
super(props)
this.onClick = this.onClick.bind(this)
}
onClick(e){
console.log(e)
}
render(){
return (
<button onClick = {this.onClick} />
)
}
}

3、使用箭头函数

箭头函数可以绑定this对象,大大减少显式绑定this对象的写法(call,apply,bind)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import React from 'react';
export default class Component extends React.Component {
constructor(props){
super(props)
}
onClick(e){
console.log(e)
}
render(){
return (
<button onClick = {() => this.onClick} />
)
}
}

4、使用函数绑定运算符’::’

箭头函数并不是适合运用于所有的场合,所以ES7提出了“函数绑定”(function bind)运算符,用来取代call、apply、bind调用

函数绑定运算符是并排的两个双冒号(::),双冒号左边是一个对象,右边是一个函数。该运算符会自动将左边的对象,作为上下文环境(即this对象),绑定到右边的函数上面。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import React from 'react';
export default class Component extends React.Component {
constructor(props){
super(props)
}
onClick(e){
console.log(e)
}
render(){
return (
<button onClick = {::this.onClick} />
)
}
}

传递参数

将bind中的第二个参数作为需要传递的数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import React from 'react';
export default class Component extends React.Component {
constructor(props){
super(props)
}
onClick(name,e){
console.log(name) //{'name':'Jack'}
}
render(){
return (
<button onClick = {this.onClick.bind(this,{'name':'Jack'})} />
)
}
}