我正在嘗試使用 React Native 中的 Map 函式從 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>
);
}
}
但我收到以下錯誤:
未定義不是一個物件(評估'_this.props.navigation')
我究竟做錯了什么?
uj5u.com熱心網友回復:
您可以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
}
uj5u.com熱心網友回復:
你可以試試 :) 我已經將導航作為顯示功能中的道具傳遞,破壞它并重新使用作為訪問 this.props.navigation 的捷徑..
在 a 中提取點擊的邏輯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>
);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/387119.html
標籤:javascript 反应原生
上一篇:如何在回圈中等待方法的執行結束?
下一篇:Gradle-將任務輸出寫入檔案
