HTML 通常写法是:
<button onclick="activateLasers()">
激活按钮
</button>
React 中写法为:
<button onClick={activateLasers}>
激活按钮
</button>
看以上会发现react传入的是函数名,不加(),如果加了会直接执行。
关于bind
1当你使用 ES6 class 语法来定义一个组件的时候,事件处理器会成为类的一个方法
2你必须谨慎对待 JSX 回调函数中的 this,类的方法默认是不会绑定 this 的。如果你忘记绑定 this.handleClick 并把它传入 onClick, 当你调用这个函数的时候 this 的值会是 undefined。默认的this指向的是全局,全局中没有你定义在组建里面的函数。bind后的this指向的是上下文,也就是这个组件,这个组件才有你所需要的方法
3这并不是 React 的特殊行为;它是函数如何在 JavaScript 中运行的一部分。通常情况下,如果你没有在方法后面添加 () ,例如 onClick={this.handleClick},你应该为这个方法绑定 this。
4在构造函数中bindthis或者在onclick调用的时候bind
this.handleClick = this.handleClick.bind(this);
5还可以如果使用 bind 让你很烦,这里有两种方式可以解决。如果你正在使用实验性的属性初始化器语法,你可以使用属性初始化器来正确的绑定回调函数:
class LoggingButton extends React.Component {
// 这个语法确保了 `this` 绑定在 handleClick 中
// 这里只是一个测试
handleClick = () => {
console.log('this is:', this);
}
render() {
return (
<button onClick={this.handleClick}>
Click me
</button>
);
}
}
如果你没有使用属性初始化器语法,你可以在回调函数中使用 箭头函数:
class LoggingButton extends React.Component {
handleClick() {
console.log('this is:', this);
}
render() {
// 这个语法确保了 `this` 绑定在 handleClick 中
return (
<button onClick={(e) => this.handleClick(e)}>
Click me
</button>
);
}
}
这个是一个其他总结
this.x = 9;
var module = {
x: 81,
getX: function() { return this.x; }
};
module.getX(); // 返回 81
var retrieveX = module.getX;
retrieveX(); // 返回 9, 在这种情况下,"this"指向全局作用域
// 创建一个新函数,将"this"绑定到module对象
// 新手可能会被全局的x变量和module里的属性x所迷惑
var boundGetX = retrieveX.bind(module);
boundGetX(); // 返回 81
即使用bind()方法是为了将函数中的this与当前组件绑定,在该处理函数中的this时刻都指向该组件,避免出现问题。
同时,如今进行this绑定除了bind外还有其他两种方式
构造函数内绑定
在构造函数 constructor 内绑定this,好处是仅需要绑定一次,避免每次渲染时都要重新绑定,函数在别处复用时也无需再次绑定
import React, {Component} from 'react'
class Test extends React.Component {
constructor (props) {
super(props)
this.state = {message: 'Allo!'}
this.handleClick = this.handleClick.bind(this)
}
handleClick (e) {
console.log(this.state.message)
}
render () {
return (
<div>
<button onClick={ this.handleClick }>Say Hello</button>
</div>
)
}
}
箭头函数方式
箭头函数则会捕获其所在上下文的this值,作为自己的this值,使用箭头函数就不用担心函数内的this不是指向组件内部了。可以按下面这种方式使用箭头函数:
class Test extends React.Component {
constructor (props) {
super(props)
this.state = {message: 'Allo!'}
}
handleClick (e) {
console.log(this.state.message)
}
render () {
return (
<div>
<button onClick={ ()=>{ this.handleClick() } }>Say Hello</button>
</div>
)
}
}
作者:欧皇喜羊羊
链接:https://www.jianshu.com/p/0b6ac20d9686
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。