我有一个 TabNavigator,每个选项卡中都有一个 StackNavigator。在 StackNavigator 内部,我有屏幕。每个 Tab 中的屏幕不直接相互调用; TabNavigator 处理按下选项卡时的屏幕变化。
在第一个选项卡中,如果用户单击一个按钮,则会创建一些数据。如果用户随后导航到第二个选项卡,我想将此数据传递到第二个选项卡中的屏幕。
下面是代码演示:
import React from 'react';
import { Button, Text, View } from 'react-native';
import {
createBottomTabNavigator,
createStackNavigator,
} from 'react-navigation';
class HomeScreen extends React.Component {
doIt = () => {
this.props.navigation.setParams({results: ['one', 'two']}); // <--- set data when user clicks button.
}
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
{/* other code from before here */}
<Button
title="Set Results"
onPress={this.doIt}
/>
</View>
);
}
}
class SettingsScreen extends React.Component {
render() {
console.log(this.props.navigation); // <--- console out when user clicks on this tab
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Settings</Text>
</View>
);
}
}
const HomeStack = createStackNavigator({
Home: HomeScreen,
});
const SettingsStack = createStackNavigator({
Settings: SettingsScreen,
});
export default createBottomTabNavigator(
{
Home: HomeStack,
Settings: SettingsStack,
},
{
}
);
this.props.navigation.state.params
永远不会获取第二个 Tab 中的数据 results
。它甚至没有 key ,所以如果我尝试访问 this.props.navigation.state.params.results
,它将是未定义的。
这令人困惑,因为我认为 props.navigation
是 passed to all screens automatically .
如何仅使用 react-navigation 通过 TabNavigator 将数据从一个屏幕传递到另一个屏幕?我已经看到说要使用 Redux 的答案,但如果我只想在不同的 react 导航器中跨屏幕保持一些状态,我不想导入另一个库。
最佳答案
this.props.navigation.state.params
似乎只能使用 old 一个参数?可能吗?试试这个:
doIt = () => {
this.props.navigation.setParams({results: 'one'}); // <--- set data when user clicks button.
}
console.log(this.props.navigation.state.params.results);
关于react-native - React Navigation - 如何在 TabNavigator 中跨不同屏幕传递数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50412762/