Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

javascript - React Navigation pass props in TabNavigator

I have props what are loaded from the server on the initial screen. I want to pass them to the rest of the tab screens. However, I have not found any examples online. I know of the screenProps, but have no idea how to set it up. All methods I have tried, have resulted in errors.

const EProj = TabNavigator({
  Home: { screen: HomeScreen },
  Map: { screen: MapG },
  Login: { screen: Login },
  Profile: { screen: Profile },
}, {
  tabBarPosition: 'bottom',
  animationEnabled: true,
  tabBarOptions: {
    activeTintColor: '#1abc9c',
  },
});

This is my screen setup. Where should I place the screenProps?

<EProj
  screenProps={cats}
/>

Any good examples how to set this up would be helpful. Thanks in advance.

HomeScreen setup:

class HomeScreen extends React.Component {
  static navigationOptions = {
    tabBarLabel: 'Home',
  };

...

  componentWillMount(){
    console.log("Starting to load assets from server!");
    this.onLoadCats(); /*starts asset loading*/
  }

  render() {
    return (
      <View style={styles.container}>

        <Text>Welcome to alpha 1.17 This is hard system test.</Text>
        <AssetsLoad catsL={this.state.catsL} />
      </View>
    );
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What you can do is create a higher order component that can return the navigation, and in that component's componentDidMount, you can load the data and pass it through screenProps.

Example

const EProj = TabNavigator({
  Home: { screen: HomeScreen },
  Map: { screen: MapG },
  Login: { screen: Login },
  Profile: { screen: Profile },
}, {
  tabBarPosition: 'bottom',
  animationEnabled: true,
  tabBarOptions: {
    activeTintColor: '#1abc9c',
  },
});

class MainNavigation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {cats: []};
  }
  componentDidMount() {
    this.onLoadCats().then((cats) => this.setState({ cats: cats }));
  }
  render() {
    return(<EProj screenProps={{ cats: this.state.cats}} />
  }
}

// Now you can do in your screens
console.log(this.props.screenProps.cats);

/* This is next line is wrong, please check update above */ 
/* console.log(this.props.navigation.state.params.cats); */

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...