最近,我开始使用React Native0.61.5
和React导航5.x
。现在,我需要将父函数传递给子屏幕。例如,我想通过按嵌套在StackNavigator中的TabNavigator选项卡中的按钮来更改导航栏图标。以前(3.x版导航)getActiveChildNavigationOptions
用于满足我的需求,但现在已将其删除。因此,实现此目标的唯一方法是将自定义函数传递给子组件。
在示例代码中,我想从更改XXXXXXXX
为YYYYYYYYY
:
const TabA = ({ route }) => (
<View>
<Text>Tab A</Text>
<Button
title="Change header"
onPress={() => route.params.setHeaderRightName("YYYYYYYYY")}/>
</View>
)
const TabB = () => <><Text>Tab B</Text></>
const Tabs = createBottomTabNavigator();
const TabsNavigator = ({ navigation }) => {
const [headerRightName, setHeaderRightName] = useState("XXXXXXXX");
useLayoutEffect(() => navigation.setOptions({
headerRight: () => <MyNavIcon name={headerRightName}/>
}), [headerRightName]);
return (
<Tabs.Navigator>
<Tabs.Screen name="tab-a" component={TabA} initialParams={{ setHeaderRightName }} />
<Tabs.Screen name="tab-b" component={TabB} />
</Tabs.Navigator>
);
}
const Stack = createStackNavigator();
export default App = () => (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="tabs" component={TabsNavigator} />
<Stack.Screen name="another-screen" component={AnotherScreen} />
</Stack.Navigator>
</NavigationContainer>
)
一切正常,但我收到此警告:
全文:
Non-serializable values were found in the navigation state, which can break usage such as persisting and restoring state. This might happen if you passed non-serializable values such as function, class instances etc. in params. If you need to use components with callbacks in your options, you can use 'navigation.setOptions' instead. See https://reactnavigation.org/docs/troubleshooting#i-get-the-warning-non-serializable-values-were-found-in-the-navigation-state for more details.
因此,如果警告说我无法使用路由参数传递功能,该如何将功能从父级传递给子级?
警告中的链接指向的文档页面显示:
如果您不使用状态持久化或不使用接受参数形式的功能的深层链接到屏幕,则可以忽略该警告。要忽略它,可以使用YellowBox.ignoreWarnings。
因此,就我而言,我可以忽略此警告并以安全的方式传递认为路由参数有用的函数。
YellowBox.ignoreWarnings([
'Non-serializable values were found in the navigation state',
]);
或对本机0.63和更高版本进行反应:
LogBox.ignoreLogs([
'Non-serializable values were found in the navigation state',
]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句