TabNavigator pass different param from each screen

2019-07-23 04:24发布

问题:

I have Question. How can I pass specific param from each screen to the StackNavigator header in order to come out different kind of components when reached the screen.

I have done some research about this kind of question, but there are not much info that can help me. So I posted here to find some help, hope there are someone who can guide me. Thanks a lot.

const mainNav = TabNavigator({
  Home: { 
    screen: HomeScreen,
    param:{
      tabval:1
    }
  },
  Live: {
   screen: LiveScreen,
   param:{
      tabval:2
    }
  },
  Radio: {
   screen: RadioScreen,
   param:{
      tabval:3
    }
  },
} );

function DifferentComponents(tabval){
  if(tabval == 1){
    //do something
  }else if(tabval == 2){
    //do something
  }else{
    //do something
  }
}

export const mainStack = StackNavigator({
  Home: { 
    screen: mainNav,
    navigationOptions: {
      header: (
        <View style={styles.topnavscrollview}>
          <View style={{width:300}}>
            <ScrollView horizontal={true} showsHorizontalScrollIndicator={false}>
              {this.DifferentComponents(tabval)} <-- Change this when switch to Live tab or others
            </ScrollView>
          </View>
        </View>
      ),
    },
  },
  Content: { screen: ContentScreen },
});

回答1:

You can pass in the custom header value as a prop to the component.
Then put something like this at the top the component that you want to customize the header for:

class Home extends React.Component {    

  // dynamically set header title when component mounts
  static navigationOptions = (props) => {
    const title = props.myTitleForThisComponent;
    return { title }
  }

  render(){
  // render stuff..
  }
}

When you navigate to the component via a StackNavigator link, any props that you pass into the component will be available as this.props.navigation.state.params.

For example, if you navigate to your component via StackNavigator like this:

this.props.navigation.navigate(
    'Home',
     /* below passes into the "Home" component as: this.props.navigation.state.params.title */
     { myCustomTitle: "hello there" }
)}

Then you can create a custom title for the Home page component like this:

  static navigationOptions = ({ navigation }) => {
    const { myCustomTitle } = navigation.state.params;
    return { title: `${myCustomTitle} !!`}
  }

hello there !!

Note: when you define your StackNavigator, you do not need to include the option navigationOptions.title, since you are add it dynamically when the component mounts.
However, you can provide generic navigationOptions values within the StackNavigator definition, to provide a "default" values for components that do not add/re-write them dynamically.