react事件处理

内容导图

配置

事件处理属性名使用驼峰写法(原生html通用写法为小写)

1
2
3
<div>
<a href="#" onClick={handleClick} > click me </a>
</div>

事件处理函数体内的this

js的类方法默认不绑定this,可通过下面两种方法绑定this

1、在构造函数中绑定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};

// 为了在handleClick中使用 `this`,这个绑定是必不可少的
this.handleClick = this.handleClick.bind(this);
}

handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}

render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}

ReactDOM.render(
<Toggle />,
document.getElementById('root')
);

2、将类方法定义为箭头函数

1
2
3
4
5
6
7
8
9
10
11
handleClick = () => {//箭头函数会默认绑定this
console.log('this is:', this);
}

render() {
return (
<button onClick={this.handleClick}>
Click me
</button>
);
}

3、在回调中使用箭头函数

1
2
3
4
5
6
7
8
9
10
11
12
13
handleClick() {
console.log('this is:', this);
}

render() {
// 此语法确保 `handleClick` 内的 `this` 已被绑定。
// 当回调函数作为 prop 传入子组件时,这些组件可能会进行额外的重新渲染,从而导致性能问题
return (
<button onClick={(e) => this.handleClick(e)}>
Click me
</button>
);
}

阻止默认行为

使用e.preventDefault()来阻止默认行为,而不是return false。

1
2
3
4
5
6
7
8
9
10
11
12
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}

return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}

给事件处理函数传参

1
2
3
4
5
1、使用箭头函数,需要显式传递e
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>

2、使用bind方式,e会最为最后一个参数默认传进去
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>