1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > React事件绑定几种方法测试

React事件绑定几种方法测试

时间:2023-12-01 20:50:01

相关推荐

React事件绑定几种方法测试

前提

es6写法的类方法默认没有绑定this,不手动绑定this值为undefined。

因此讨论以下几种绑定方式。

一、构造函数constructor中用bind绑定

class App extends Component {constructor (props) {super(props)this.state = {t: 't'}// this.bind1 = this.bind1.bind(this) 无参写法this.bind1 = this.bind1.bind(this, this.state.t)}// 无参写法 // bind1 () {// console.log('bind1', this)// }bind1 (t, event) {console.log('bind1', this, t, event)}render () {return (<div><button onClick={this.bind1}>打印1</button></div>)}}

二、在调用的时候使用bind绑定this

bind2 (t, event) {console.log('bind2', this, t, event)}render () {return (<div><button onClick={this.bind2.bind(this, this.state.t)}>打印2</button></div>)}// 无参写法同第一种

三、在调用的时候使用箭头函数绑定this

bind3 (t, event) {console.log('bind3', this, t, event)}render () {return (<div>// <button onClick={() => this.bind3()}>打印3</button> 无参写法<button onClick={(event) => this.bind3(this.state.t, event)}>打印3</button></div>)}

四、使用属性初始化器语法绑定this

bind4 = () =>{console.log('bind4', this)}render () {return (<div><button onClick={this.bind4}>打印4</button>// 带参需要使用第三种方法包一层箭头函数</div>)}

附加::方法(不能带参,stage 0草案中提供了一个便捷的方案——双冒号语法)

bind5(){console.log('bind5', this)}render() {return (<div><button onClick={::this.bind5}></button></div>)}

方法一优缺点

优点:

只会生成一个方法实例;

并且绑定一次之后如果多次用到这个方法也不需要再绑定。

缺点:

即使不用到state,也需要添加类构造函数来绑定this,代码量多;

添加参数要在构造函数中bind时指定,不在render中。

方法二、三优缺点

优点:

写法比较简单,当组件中没有state的时候就不需要添加类构造函数来绑定this。

缺点:

每一次调用的时候都会生成一个新的方法实例,因此对性能有影响;

当这个函数作为属性值传入低阶组件的时候,这些组件可能会进行额外的重新渲染,因为每一次都是新的方法实例作为的新的属性传递。

方法四优缺点

优点:

创建方法就绑定this,不需要在类构造函数中绑定,调用的时候不需要再作绑定;

结合了方法一、二、三的优点。

缺点:

带参就会和方法三相同,这样代码量就会比方法三多了。

总结

方法一是官方推荐的绑定方式,也是性能最好的方式。

方法二和方法三会有性能影响,并且当方法作为属性传递给子组件的时候会引起重新渲染问题。

方法四和附加方法不做评论。

大家根据是否需要传参和具体情况选择适合自己的方法就好。

谢谢阅读。

更多专业前端知识,请上【猿2048】

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。