繁体   English   中英

React Conditional Render和Navbar

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM