[英]React Native Navigation inside Map Function
我正在尝试在 React Native 中使用 Map function 从 JSON 数据生成卡片。
我希望能够通过单击此卡导航到另一个页面。
这是我正在尝试的解决方案:
function display() { return restaurant.map((item) => { return( <TouchableHighlight onPress={() => this.props.navigation.navigate('Restaurant')}> <View style={styles.card}> <View style={styles.cardHeadText}> <Text style={styles.title}> { item.name } </Text> <Text> { item.type } </Text> </View> </View> </TouchableHighlight> ); }); } class RestaurantCard extends Component { render() { return ( <View style={styles.container}> {display()} </View> ); } }
但我收到以下错误:
未定义不是 object(评估“_this.props.navigation”)
我究竟做错了什么?
您可以将this
作为参数传递给map
function,如文档中所述: https://developer.mozilla.org/en_Objects/docsReference/Webmap/
function display() {
return restaurant.map((item) => {
return(
<TouchableHighlight onPress={() => this.props.navigation.navigate('Restaurant')}>
<View style={styles.card}>
<View style={styles.cardHeadText}>
<Text style={styles.title}>
{ item.name }
</Text>
<Text>
{ item.type }
</Text>
</View>
</View>
</TouchableHighlight>
);
}, this); // over here
}
你可以试试:) 我已经通过导航作为显示 function 中的道具,将其破坏并重新用作访问 this.props.navigation 的简短内容。
在handler
中提取点击的逻辑使其易于阅读和控制,您可以更轻松地添加验证和其他内容。
function display(props) { const { navigation } = props const handlerClick = (item) => { /* all the content of item (name, and type) will be passed in props of the other page component */ navigation.navigate("Restaurant", {...item}) } return restaurant.map((item) => { return( <TouchableHighlight onPress={() => handlerClick(item)}> <View style={styles.card}> <View style={styles.cardHeadText}> <Text style={styles.title}> { item.name } </Text> <Text> { item.type } </Text> </View> </View> </TouchableHighlight> ); }); } class RestaurantCard extends Component { render() { return ( <View style={styles.container}> {display(this.props.navigation)} </View> ); } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.