jsp网站首页那栏怎么做,网站建设高端定制,阐述什么是网站,微商城运营的主要工作转载自 React绑定this的三种方式
React可以使用React.createClass、ES6 classes、纯函数3种方式构建组件。使用React.createClass会自动绑定每个方法的this到当前组件#xff0c;但使用ES6 classes或纯函数时#xff0c;就要靠手动绑定this了。接下来介绍React中三种绑定th…转载自 React绑定this的三种方式
React可以使用React.createClass、ES6 classes、纯函数3种方式构建组件。使用React.createClass会自动绑定每个方法的this到当前组件但使用ES6 classes或纯函数时就要靠手动绑定this了。接下来介绍React中三种绑定this的方法
bind()
Function.prototype.bind(thisArg [, arg1 [, arg2, …]]) 是ES5新增的函数扩展方法bind()返回一个新的函数对象该函数的this被绑定到thisArg上并向事件处理器中传入参数
import React, {Component} from reactclass Test extends React.Component {constructor (props) {super(props)this.state {message: Allo!}}handleClick (name, e) {console.log(this.state.message name)}render () {return (divbutton onClick{ this.handleClick.bind(this, 赵四) }Say Hello/button/div)}
}
要注意的是跟在this或其他对象后面的参数之后它们会被插入到目标函数的参数列表的开始位置传递给绑定函数的参数会跟在它们的后面。
构造函数内绑定
在构造函数 constructor 内绑定this好处是仅需要绑定一次避免每次渲染时都要重新绑定函数在别处复用时也无需再次绑定
import React, {Component} from reactclass 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 (divbutton 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 (divbutton onClick{ (){ this.handleClick() } }Say Hello/button/div)}
}
这种方式有个小问题因为箭头函数总是匿名的如果你打算移除监听事件可以改用以下方式
class Test extends React.Component {constructor (props) {super(props)this.state {message: Allo!}}handleClick (e) {console.log(this.state.message)}render () {return (divbutton onClick{ this.handleClick }Say Hello/button/div)}
}不过在Classes中直接赋值是ES7的写法ES6并不支持只用ES6的话可以用下面写法
class Test extends React.Component {constructor (props) {super(props)this.state {message: Allo!}this.handleClick (e) {console.log(this.state.message)}}render () {return (divbutton onClick{ this.handleClick }Say Hello/button/div)}
}三种方法都能实现this的绑定至于用哪种方式还跟着自己的习惯来。
》》 更多干货 》》
参考 MDN文档 Function.prototype.bind() MDN稳定 Arrow Functions