如何通过反应导航动态创建屏幕

时间:2018-07-27 15:51:37

标签: javascript react-navigation

我想在堆栈的屏幕DetailsS​​creen上动态创建一些MeScreen。我得到了:

  

无法读取未定义的属性“导航”

和:

  

未处理的JS异常:无法读取未定义的属性“导航”

当我按下MeScreen上的“转到ItemScreen”按钮以推送ItemScreen时,出现

错误。以下是演示代码。

//App.js     
import React from 'react';
import { 
  View
  ,Text
  ,Button 
  ,StyleSheet
  ,Alert
  } from 'react-native';
import { 
  createStackNavigator 
  ,createMaterialTopTabNavigator
} from 'react-navigation';

class HomeScreen extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Home Screen</Text>
        <Button
          title="Go to Details"
          onPress={() => this.props.navigation.push('Details')}
        />
      </View>
    );
  }

}

class ItemScreen extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>ItemScreen</Text>
      </View>
    );
  }

}

class DetailsScreen extends React.Component {

 getTabsMapping() {
    var mapping = new Map()

    //dynamic create screen mapping
    for (var i = 0; i < 4; i++) {
      mapping[i] = MeScreen
    }

    return mapping
  }

  getTabs() {
    var mapping = this.getTabsMapping()
    Tabs = createMaterialTopTabNavigator(
      mapping, {
        animationEnabled: true,
        tabBarPosition: 'top',
        swipeEnabled: true,
        backBehavior: 'none',
        tabBarOptions: {
          activeTintColor: 'orange',
          inactiveTintColor: 'gray',
          showIcon: true,
          indicatorStyle: {
            height: 0,
          },
          style: styles.tabBar,
          tabStyle: styles.tabBarItem,
          labelStyle: styles.tabBarLabel,
          pressColor: 'gray',
          pressOpacity: 0.8,
          upperCaseLabel: false,
        },
      }
    )

    return Tabs
  }

  render() {
    var Tabs = this.getTabs()
    return ( < Tabs / > )
  }
}



class MeScreen extends React.Component {

  static navigationOptions = {
    title:'Mine',
    headerTintColor:'yellow',
  };

  onPressed() {

    //crashed here
    this.props.navigation.push('ItemScreen')
  }

  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>MeScreen</Text>
        <Button
          title="Go to ItemScreen"
          onPress={this.onPressed}
        />
      </View>
    );
  }

}




const styles = StyleSheet.create({
  tabBarImage: {
    width: 24,
    height: 24,
  },
  tabBar: {
    backgroundColor: 'white',
  },
  tabBarLabel: {
    fontSize: 12,
  },
  tabBarItem: {
    height: 56,
  },
})

const RootStack = createStackNavigator({
    Home: HomeScreen,
    Details: DetailsScreen,
    ItemScreen: ItemScreen,
},
  {
    initialRouteName: 'Home',
  }
);


export default class App extends React.Component {
  render() {
    return <RootStack />;
  }
}

0 个答案:

没有答案