[英]How to render a component using onPress()?
一旦我點擊一個按鈕,我想渲染/導航到一個新的組件,將道具傳遞給它。
第一次嘗試- 語法錯誤
{
this.state.history ? (
this.state.history.map(data => {
return (
<View style={styles.historyUnit}>
<TouchableOpacity
onPress={return <Map2 latitude={data1} longitude={data1} />;}
>
{" "}
</TouchableOpacity>
</View>
);
})
) : (
<ActivityIndicator size="large" color="#0000ff" />
);
}
第二次嘗試- 組件未呈現
onPress={this.showHistory}
showHistoryUnit = (data1, data2) => {
return <Map2 latitude={data1} longitude={data1} />;
};
第三次嘗試- 我導航到組件,但沒有傳遞道具
showHistoryUnit = (data1, data2) => {
this.props.navigation("map2")
return <Map2 latitude={data1} longitude={data1} />;
};
我怎樣才能做到這一點?
this.state = {
selectedId = 0
}
this.state.history.map(data => {
return (
<View style={styles.historyUnit}>
<TouchableOpacity
onPress={() => {
this.setState({ selectedId: data.id })
}}
>
{data.id === this.state.selectedId &&
<Map2 latitude={data1} longitude={data1} />
}
</TouchableOpacity>
</View>
);
})
它只是同時返回一個 Map2 組件。 如果您想連續返回 Map2,請改用數組
理想情況下,您應該使用模態或類似方式來顯示特定的Map
信息,但這也可以使用組件內部狀態來實現。
state = {
mapComponent: null,
};
if (this.state.history) {
return this.state.mapComponent || this.state.history.map(data => {
return (
<View style={styles.historyUnit}>
<TouchableOpacity
onPress={() => this.setState({ mapComponent: <Map2 latitude={data1} longitude={data1} /> })}
>
{" "}
</TouchableOpacity>
</View >
);
})
}
return <ActivityIndicator size="large" color="#0000ff" />;
你可以使用帶有 setState 的三元運算符就像當你在按鈕中設置一些狀態然后使用三元運算符來顯示視圖時this.state.history
理想情況下檢查你的this.state.history
,它應該是一個布爾值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.