React Native Navigation inside Map Function



我正在尝试使用React Native中的Map函数从JSON数据生成Card。

我希望能够通过点击这张卡片导航到另一个页面。

这就是我正在尝试的解决方案:

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>


);
}
}

但我得到以下错误:

Undefined不是对象(正在评估"_this.props.navigation"(

我做错了什么?

您可以将this作为参数传递给map函数,如文档中所述:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

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
}

您可以尝试一下:(我通过了导航作为显示功能中的道具,破坏了它,并作为一个简短的简短提示重新使用。道具。导航。

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

最新更新