React 条件渲染和导航栏

Nex*_*xus 5 javascript reactjs react-native

我通过主渲染函数中的状态和 switch 语句控制应在应用程序屏幕上显示哪些组件。我正在用反应本机写这篇文章,但这是一个反应结构问题。

我还有一个导航栏组件,理想情况下我希望仅在用户单击导航栏本身中的链接时重新呈现,但我不知道现在如何设置 switch 语句来实现此目的,它似乎我每次都必须重新渲染导航栏,具体取决于状态满足的条件。

我的问题是,有没有一种方法可以让我仍然可以在渲染方法中使用组件的条件渲染,就像下面一样,并且有一个组件始终渲染在屏幕顶部,例如导航栏?我知道使用 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;

    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Hem*_*ari 3

始终保持渲染尽可能干净。

您可以使用 && 运算符来执行相同的操作,而不是使用 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>
        )}
    )

  }
Run Code Online (Sandbox Code Playgroud)