繁体   English   中英

React-Navigation:如何在TabNavigation中的选项卡之间传递数据?

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

我在tabNavigation中有两个标签

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

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

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

所以我想将选项卡从HomeView切换到SettingView

//在主视图中

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

通过按钮操作,并希望发送如下数据。

//在设置视图中

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

SettingView处得到falsenull ,需要一种正确的方法来将数据从一个选项卡获取到另一个?

我们使用this.props.navigation从上一个标签中获得道具。

在传递数据时添加

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

要在“设置”屏幕上访问以上数据,请在componentDidMount方法或render方法中添加以下代码

this.props.navigation.state.params.someFlag //您可以在此处以true的方式访问someFlag

您需要在SettingView中使用dangerouslyGetParent()地GetParent dangerouslyGetParent() this.props.navigation.navigate将参数发送给父对象,而不是屏幕。 SettingView中的代码将是:

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

您可以使用screenProps

ScreenProps使用情况链接页面

  • screenProps-将额外的选项传递给子屏幕

//主视图

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

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

export default YourApp

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

//在设置视图中

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

    return (
      <View>
        <Text>{screenProps.someFlag}</Text>
        <Text>{screenProps.data}</Text>
      </View>
    )
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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