简体   繁体   中英

React-Navigation: How to pass data between tabs in TabNavigation?

I Have two tabs in tabNavigation

const HomeStack = createStackNavigator({
    Home: HomeView
});

const SettingStack = createStackNavigator({
    Setting: SettingView
});

const TabNavigator = createBottomTabNavigator({
    Home: HomeStack,
    Setting: SettingStack
});

So I want to switch tab from HomeView to SettingView

// IN HOME VIEW

this.props.navigation.navigate('Setting', {
    someFlag: true,
    data: "SET"
});

via button action and want to send some data as below.

// IN SETTING VIEW

const { navigation } = this.props;
const openPCPSchedule = navigation.getParam("someFlag", false);
const data = navigation.getParam("data", null);
console.log("NAVI PARAMS: ", openPCPSchedule); // false
console.log("NAVI data: ", data); // null

Getting false and null at SettingView , Need a correct way to get data from one to tab to other?

We get props from previous tab using this.props.navigation.

While passing data add

this.props.navigation.navigate('Setting', {
    someFlag: true,
    data: "SET"
});

To access above data on Setting screen add following code in componentDidMount method or in render method

this.props.navigation.state.params.someFlag // You can access someFlag as true here

You need to use dangerouslyGetParent() in SettingView. this.props.navigation.navigate sends params to the parent, not to the screen. The code in SettingView will be:

const { navigation } = this.props;
const openPCPSchedule = navigation.dangerouslyGetParent().getParam("someFlag", false);
const data = navigation.dangerouslyGetParent().getParam("data", null);

You can use screenProps

ScreenProps Usage Link Page

  • screenProps - Pass down extra options to child screens

//MAIN VIEW

class YourApp extends Component {
  render() {
    const screenProps = {
         someFlag: true,
         data: "SET"
    }

    return (
      <TabNavigator screenProps={screenProps} />
    )
  }
}

export default YourApp

AppRegistry.registerComponent('YourApp', () => YourApp);

// IN SETTING VIEW

class SettingScreen extends Component {
  render() {
    const { navigation, screenProps } = this.props

    return (
      <View>
        <Text>{screenProps.someFlag}</Text>
        <Text>{screenProps.data}</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