javascript - 请教react native的写法中,用bind和用箭头函数哪个好?
本文介绍了javascript - 请教react native的写法中,用bind和用箭头函数哪个好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
写法1:
<XXView xxxx={this.xxA.bind(this)} />
写法2:
constructor(props) {
super(props);
this.xxA= this.xxA.bind(this);
}
写法3:
xxA = ()=>{};
<XXView xxxx={this.xxA} />
写法4:
<XXView xxxx={()=>this.xxA} />
1和2一样,3和4一样吧。
那么实际中大家更倾向哪种写法?
求教用箭头函数和用bind,有什么区别呢?哪个更好呢?
解决方案
我发觉2和3的做法,会触发xxA中的方法。
如果在xxA中涉及到改动state(当然不规范),比如来个toString()之类的,更明显,就会触发
Cannot update during an existing state transition警告。
我的源码如下:
onPressItem(sourceItem){
console.log('onPressItem');
// toastShort('点击了'+sourceItem.name);
}
renderItem(sourceItem){
return(
<TouchableOpacity onPress={
this.onPressItem(sourceItem)
} >
<View style={styles.containerItem}>
<Text style={{ fontSize: 18, textAlign: 'left', color: '#87CEFA', }}>
{sourceItem.name}
</Text>
</View>
</TouchableOpacity>
);
}
constructor(props) {
super(props);
this.state = {
dataSource: ds.cloneWithRows([]),
};
this.onPressItem = this.onPressItem.bind(this);
}
页面一旦render,什么都不做,console.log('onPressItem');就会被执行多次。
而如果我使用
() => this.onPressItem(sourceItem)
就不会。
关于这个问题,我在bind和箭头函数-哪个更好呢 的帖子里也询问了。得到了不同答案。
并且我观察到某位实际从事React-Native开发的,在他的代码中,Main.js ,也是和其他不同,使用了箭头函数。
非常疑惑这几种的区别。希望能有真正了解的人谈一下。
这篇关于javascript - 请教react native的写法中,用bind和用箭头函数哪个好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文