[英]How to handle onPress function react
I am using react native with NativeBase components, and I am having a problem calling my _doStuff function. 我正在对NativeBase组件使用本机响应,并且在调用_doStuff函数时遇到问题。 I tried to call 我试图打电话
onPress={this._doStuff.bind(this)}
but keep receiving 但继续接受
Cannot read properly 'doStuff' of undefined 无法正确读取未定义的“ doStuff”
_doStuff(){
console.log('Hi');
}
_getList() {
return this.state.listData.map(function(data, i){
return(
<View key={i}>
<ListItem style={styles.listItemContain}>
<Button transparent onPress={this._doStuff.bind(this)}>
<View>
<Thumbnail source={{uri: data.icon}} style={styles.thumbnailStyle}/>
<Text style={styles.title}>{data.name}</Text>
<Text note style={styles.text}>{data.vicinity}</Text>
</View>
</Button>
</ListItem>
</View>
);
});
this
context is lost inside the .map loop. this
上下文在.map循环内丢失。 if you are using ES6, try to use fat arrow functions as shown below. 如果使用的是ES6,请尝试使用粗箭头功能 ,如下所示。
_getList() { return this.state.listData.map((data, i) => { return( <View key={i}> <ListItem style={styles.listItemContain}> <Button transparent onPress={this._doStuff.bind(this)}> <View> <Thumbnail source={{uri: data.icon}} style={styles.thumbnailStyle}/> <Text style={styles.title}>{data.name}</Text> <Text note style={styles.text}>{data.vicinity}</Text> </View> </Button> </ListItem> </View> ); });
if you cant use ES6 on your project due to various reasons use alternative approach(old school) as shown below... 如果由于各种原因而不能在项目中使用ES6,请使用替代方法(旧学校),如下所示...
_getList() { return this.state.listData.map(function(data, i){ var that = this; return( <View key={i}> <ListItem style={styles.listItemContain}> <Button transparent onPress={that._doStuff.bind(that)}> <View> <Thumbnail source={{uri: data.icon}} style={styles.thumbnailStyle}/> <Text style={styles.title}>{data.name}</Text> <Text note style={styles.text}>{data.vicinity}</Text> </View> </Button> </ListItem> </View> ); });
I would make a wager that the context of your _getList
function does not have the context of the React Component that you are thinking. 我敢打赌,您_getList
函数的上下文不具有您正在考虑的React组件的上下文。 If you are using ES6 classes and would like to get autobinding of the components context I would suggest using autobind-decorator . 如果您使用的是ES6类,并且希望自动绑定组件上下文,则建议使用autobind-decorator 。 If you decide to go that route here is a nice tutorial on setting it up . 如果您决定走这条路线,那么这里有个不错的教程 。
Otherwise make sure that when you call _getList
make sure to call it with either .call
or .bind
. 否则,请确保在调用_getList
时,请确保使用.call
或.bind
进行调用。
For example: 例如:
// if you are calling the function directly this._getList().call(this)
or 要么
// if you are passing the function off for another function to execute it this._getList.bind(this)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.