React-事件绑定

React事件绑定类似于DOM事件绑定,区别如下:

  1. React事件的用驼峰法命名,DOM事件事件命名是小写
  2. 通过jsx,传递一个函数作为event handler,而不是一个字符串。
  3. React事件不能通过返回false来阻止默认事件,需要显式调用preventDefault()

如下实例:


Click me

class ActionLink extends React.Component {
constructor(props) {
super(props);
}

handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}

render() {
return (
Click Me...
);
}

}

ps:React组件类的方法没有默认绑定this到组件实例,需要手动绑定。

绑定类的方法this的三种方法

在调用方法的地方直接通过调用bind方法来绑定,也可以在构造函数里面直接用bind方法绑定this.

class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = { isToggleOn: true };
//this.toggleHander = this.toggleHander.bind(this);
}

toggleHander() {
this.setState(preState => ({
isToggleOn: !preState.isToggleOn
}));
}

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

}
类的属性初始化语法(该用法还未写入es标准,有兼容问题)

class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = { isToggleOn: true };
}

toggleHander = () => {
this.setState(preState => ({
isToggleOn: !preState.isToggleOn
}));
}

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

箭头函数

class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = { isToggleOn: true };
//this.toggleHander = this.toggleHander.bind(this);
}

toggleHander() {
this.setState(preState => ({
isToggleOn: !preState.isToggleOn
}));
}

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

}
ps:推荐在构造函数中绑定相关方法的this指向,或者将方法写成类字段的形式。避免某些方法作为属性向子组件传递引起的一些问题。

posted @ 2017-08-21 09:52  joe_ice  阅读(2757)  评论(0)    收藏  举报