组件加载时间

时间:2016-11-08 04:52:55

标签: reactjs react-native

我正在使用'Navigator'并按路线渲染多个组件。我想在渲染到组件之前显示加载器(就像任何图像或文本'Loading ...'),因为这些需要时间来加载。请查看我的代码并建议我应该在哪里使用loader。     Route.js

import React from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  Image,
  ListView,
  TouchableHighlight,
  Navigator,
  TouchableOpacity, InteractionManager
} from 'react-native';

import Home from './Home';
import Tomo from './App';
import Profile from './Profile';

var SCREEN_WIDTH = require('Dimensions').get('window').width;
var BaseConfig = Navigator.SceneConfigs.FloatFromRight;
var CustomLeftToRightGesture = Object.assign({}, BaseConfig.gestures.pop, {
  snapVelocity: 10,
  edgeHitWidth: SCREEN_WIDTH,
});
var CustomSceneConfig = Object.assign({}, BaseConfig, {
  springTension: 300,
  springFriction: 10,
  gestures: {
  pop: CustomLeftToRightGesture,
}
});

export default class Route extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {renderPlaceholderOnly: true};
  }

  componentDidMount() {
    InteractionManager.runAfterInteractions(() => {
      this.setState({renderPlaceholderOnly: false});
    });
  }

  _configureScene(route) {
    return CustomSceneConfig;
  }

  render() {
    if (this.state.renderPlaceholderOnly) {
      return this._renderPlaceholderView();
    }
    return (
        <Navigator
          initialRoute={{id: 'Home'}}
          configureScene={this._configureScene}
          renderScene={this.navigatorRenderScene}

        />
    );
  }

  _renderPlaceholderView() {
    return (
      <View>
         <Text>Loading...</Text>
      </View>
    );
  }

  header() {
    return (
       <View>
         <Text>Loading...</Text>
       </View>
    );
  }

  navigatorRenderScene(route, navigator) {
    _navigator = navigator;
    switch (route.id) {
    case 'Home':
      return (<Home navigator={navigator} title="Home"/>);
    case 'Tomo':
      return (<Tomo navigator={navigator} title="Tomo"/>);
    case 'Profile':
      return (<Profile navigator={navigator} title="Profile" />);
    }
  }
}

先谢谢。

1 个答案:

答案 0 :(得分:0)

创建基本组件作为其他组件的容器(HomeTomoProfile)。此容器还包含Loading组件。因此,此容器中的每个组件都会产生加载效果。关键代码如下:

class BaseContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showLoading: true
    }
  }

  render() {
    ......

    return (
      {this.props.children}
      {
        this.state.showLoading ? <Loading /> : ''
      }
    );
  }

  ......
}