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

举报
SHQ1874009 发表于 2021/05/12 00:04:41 2021/05/12
【摘要】 文章目录 前言React中bind方法的选择 前言 在React或React-native的点击事件中,会经常用到bind(this)。比如说一个简单的React-native点击组件: export default class AwesomeProject extends Component { constructor(props){ s...


前言

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> );
  }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

在上面的代码中,我们对点击事件函数进行了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 = () => { }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

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

文章来源: shq5785.blog.csdn.net,作者:No Silver Bullet,版权归原作者所有,如需转载,请联系作者。

原文链接:shq5785.blog.csdn.net/article/details/116642922

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。