反应条件渲染和导航栏

时间:2018-09-19 17:02:33

标签: javascript reactjs react-native

我正在通过状态和主渲染函数中的switch语句来控制应在应用程序屏幕上显示的组件。我正在用react-native写这个,但这是一个react结构问题。

我还有一个Navbar组件,理想情况下,我只想在用户单击Navbar本身中的链接时才重新渲染,但是我不知道如何使用switch语句设置来实现此目的的好方法现在,似乎每次都要重新渲染Navbar,这取决于国家满足什么条件。

我的问题是,有没有一种方法可以像我在下面那样仍然可以在render方法中使用组件的条件渲染,并且可以像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;

    }
  }
}

1 个答案:

答案 0 :(得分:3)

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

您可以使用&&运算符执行相同操作,而不是使用开关盒。使用&&运算符并检查每种情况并进行相应渲染。检查下面的代码以更好地理解。

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>
        )}
    )

  }
相关问题