0
点赞
收藏
分享

微信扫一扫

ReactNative进阶(二十二):点击事件.bind(this)引发的思考

(文章目录)

一、前言

ReactReact-native的点击事件中,会经常用到bind(this)。比如说一个简单的React-native点击组件:

export default class AwesomeProject extends Component {
constructor(props){
super(props);
this.state = {
}
}

handleClick () {
console.log('this is:',this);
}

render() {
return (
<View style={styles.container}>
<Text style={styles.welcome} onPress={this.handleClick.bind(this)}>
Welcome to React Native!
</Text>
</View>

);
}
}

在上面的代码中,我们对点击事件函数进行了bind(this)操作,如果不bind(this)this会怎么样? 在这里插入图片描述 在这里插入图片描述

上图是执行了.bind(this)的,而下图是没有.bind(this)的。由执行结果可知,如果没有bind(this),在执行这个函数时,取到的this是这个text组件。

二、React中bind方法的选择

因为箭头函数与bind(this)的作用是一样的,()=>{} 这种形式的代码,语法规定就是(function(){}).bind(this),即自动添加了bind(this)。所以我们可以有4种选择:

  //写法1
<View onPress={this.handleClick.bind(this)}></View>

//写法2
constructor(props){
super(props);
this.handleClick = this.handleClick.bind(this);
}

//写法3
<View onPress={()=>this.handleClick()}>

//写法4
handleClick = () => {

}

因为bind方法会重新生成一个新函数,所以写法2和写法3每次render都会生成新的函数,所以建议使用1或4。

三、延伸阅读

  • 《ReactNative专栏》
举报

相关推荐

0 条评论