简体   繁体   中英

How to access element props react navigation

I declared a top bar element like this.

export default Class MyClass extends React.Component {
  static router = TopTabNavigator.router;

  render() {
    return() {
      <View>
        <TopTabNabiagtor
          navigation = {this.props.navigation}
          data = {this.state.data}
        />
      </View>
    }
  }
}

and still don't know how to access the data props from the creation of TopBar.

const TopTabNavigator = createMaterialTopTabNavigator(
    {
        Tab1: {
            screen: props => <Tab1 {...props} information = {props.data.information} />,
            navigationOptions: {
                tabBarLabel: "Tab1"
            }
        },
    },

Data props is undefined, I might wrong when accessing the props, did anyone know how to solve it...

You need to pass them in a specific way and that is by using screenProps , if you don't they may not get there.

The documentation explains it how to pass screenProps https://reactnavigation.org/docs/en/stack-navigator.html#navigator-props

Code Changes

In MyClass pass the props that you wish to pass in the following way

<TopTabNabiagtor
  navigation = {this.props.navigation}
  screenProps = {{data: this.state.data}}
/>

You don't need to do anything special when you create your TopTabNavigator you should just be able to access them directly in the Tabs by doing the following

this.props.screenProps.data.information

Example Code and Snack

Here is some example code, which I have also made into a handy snack for you. https://snack.expo.io/@andypandy/passing-props-through-a-navigator

App.js

import AppContainer from './MainNavigation';
export default class App extends React.Component {

    state = {
      data: { key: 2345, name: 'John'}
    };

  render() {
    return (
      <View style={{flex: 1}}>
        <AppContainer screenProps={{data: this.state.data}}/>
      </View>
    )
  }
}

MainNavigation.js

import { createMaterialTopTabNavigator, createAppContainer } from 'react-navigation';

const screens = {
  Screen1: {
    screen: props => <Screen1 {...props} /> // you can set up the screen this way
  },
  Screen2: {
    screen: Screen2 // or you can set it up this way, I usually set it up this way
  }
}

const config = {
  headerMode: 'none',
  initialRouteName: 'Screen1'
}

const MainNavigator = createMaterialTopTabNavigator(screens,config);
export default createAppContainer(MainNavigator);

Screen1.js

export default class Screen1 extends Component {

  render() {
    return (
      <View style={styles.container}>
        <Text>Screen 1</Text>
        <Text>{this.props.screenProps.data.name}</Text>
      </View>
    )
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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