gpt4 book ai didi

react-native - 如何在 React Navigation 5 中将父函数传递给子屏幕?

转载 作者:行者123 更新时间:2023-12-03 16:55:42 25 4
gpt4 key购买 nike

最近我开始使用 React Native 0.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>
)

一切正常,但我收到此警告:

enter image description here

全文:
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.

那么,如果警告说我无法使用路由参数传递函数,我该如何将函数从父级传递给子级呢?

最佳答案

警告中的链接指向的文档页面说:

If you don't use state persistence or deep link to the screen which accepts functions in params, then you can ignore the warning. To ignore it, you can use YellowBox.ignoreWarnings.


因此,就我而言,我可以忽略此警告并安全地传递认为路由参数的函数。
YellowBox.ignoreWarnings([
'Non-serializable values were found in the navigation state',
]);
或 react native 0.63 及更高版本:
LogBox.ignoreLogs([
'Non-serializable values were found in the navigation state',
]);

关于react-native - 如何在 React Navigation 5 中将父函数传递给子屏幕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60954742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com