[英]React Conditional Render and Navbar
我通過主渲染功能中的狀態和switch語句控制應該在應用程序屏幕上顯示的組件。 我用反應本地寫這個,但這是一個反應結構問題。
我還有一個Navbar組件,理想情況下,當用戶點擊Navbar本身的鏈接時,我只想重新渲染,但我不知道如何通過如何設置switch語句來實現這一點,它似乎我每次都必須重新渲染Navbar,具體取決於國家滿足的條件。
我的問題是,有沒有一種方法,我仍然可以在渲染方法中使用條件渲染組件,如下所示,並且有一個組件始終在屏幕頂部呈現,如Navbar? 我知道React Router之類的東西是可行的,但有沒有更好的方法來構建它而不使用像React Router這樣的工具或者每次都要重新渲染NavBar組件?
import React from 'react'; import GPS from './GPS/gps'; import Home from './Home'; import Photo from './Camera/Photo'; export default class App extends React.Component { constructor() { super(); this.state = { hasCameraPermission: null, type: Camera.Constants.Type.back, currentView: null, currentImage: null, navigation: 'Overview' }; this.updateNavigation = this.updateNavigation.bind(this); } updateNavigation(view) { //Update view function this.setState({currentView: view}); } render() { const { currentView } = this.state; switch(currentView) { case null: return ( <Home updateNav={this.updateNavigation} /> ); break; case 'GPS': return ( <View> <GPS /> <Text onPress={() => this.setState({currentView: null})}>Back</Text> </View> ); break; case 'Camera': return ( <Photo updateNav={this.updateNavigation} /> ); break; case 'viewPicture': return ( <View> <Image source={{uri: this.state.currentImage.uri}} style={{width: this.state.currentImage.width/10, height: this.state.currentImage.height/12}} /> </View> ); break; } } }
始終保持渲染盡可能干凈。
您可以使用&&運算符來執行相同操作,而不是使用switch case。 使用&&運算符並檢查每個案例並相應地進行渲染。 檢查以下代碼以便更好地理解。
render() {
const { currentView } = this.state;
return(
{currentView == null && (
<Home updateNav={this.updateNavigation} />
)}
{currentView == "GPS" && (
<View>
<GPS />
<Text onPress={() => this.setState({currentView: null})}>Back</Text>
</View>
)}
{currentView == "Camera" && (
<View>
<Photo updateNav={this.updateNavigation} />
</View>
)}
{currentView == "viewPicture" && (
<View>
<Image source={{uri: this.state.currentImage.uri}} style={{width: this.state.currentImage.width/10, height: this.state.currentImage.height/12}} />
</View>
)}
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.