【发布时间】:2020-05-27 21:48:24
【问题描述】:
我想通过 screenProps 在 React-navigation v5.x.x 中传递一些东西。我是 react-native 的新手之一。谁能帮帮我?
【问题讨论】:
-
对于您的下一个问题,您可能希望使用 react-navigation 标记您的问题,以便更多人可以看到它。
标签: react-native react-navigation-v5
我想通过 screenProps 在 React-navigation v5.x.x 中传递一些东西。我是 react-native 的新手之一。谁能帮帮我?
【问题讨论】:
标签: react-native react-navigation-v5
在我的情况下,我正在传递我的数据,例如:
props.navigation.navigate('toScreen', {
resumeDetail: data,
})
你可以像这样访问它:
detail = this.props.navigation.state.params.resumeDetail;
【讨论】:
React Navigation 5 中没有 screenProps。您可以使用 React's Context feature 代替在树中向下传递数据,而无需额外的 API。
https://reactnavigation.org/docs/upgrading-from-4.x#global-props-with-screenprops
【讨论】:
https://reactnavigation.org/docs/screen/#children
渲染回调以返回用于屏幕的 React Element:
<Stack.Screen name="Profile"> {(props) => <ProfileScreen {...props} />} </Stack.Screen>如果你需要传递额外的 props,你可以使用这种方法来代替组件 props。虽然我们建议使用 React 上下文来传递数据。
注意:默认情况下,React Navigation 会对屏幕组件进行优化,以防止不必要的渲染。使用渲染回调会删除这些优化。因此,如果您使用渲染回调,则需要确保为屏幕组件使用
React.memo或React.PureComponent以避免性能问题。
这是我目前使用的:
// ...
export const ScanPage = React.memo(ScanComponent);
function useScreenWithProps(
PageComponent: React.FC<Props>,
props: Props
) {
// Take note of the double arrow,
// the value useMemo returns is a function that returns a component.
return useMemo(
() => (navigationProps: NavigationProps) => (
<PageComponent {...navigationProps} {...props} />
),
[PageComponent, props]
);
}
const Stack = createStackNavigator();
const Navigator: React.FC<Props> = (props) => {
const scan = useScreenWithProps(ScanPage, props);
const activate = useScreenWithProps(ActivatePage, props);
const calibrate = useScreenWithProps(CalibratePage, props);
const success = useScreenWithProps(SuccessPage, props);
const error = useScreenWithProps(ErrorPage, props);
return (
<Stack.Navigator>
<Stack.Screen name="Scan">{scan}</Stack.Screen>
<Stack.Screen name="Activate">{activate}</Stack.Screen>
<Stack.Screen name="Calibrate">{calibrate}</Stack.Screen>
<Stack.Screen name="Success">{success}</Stack.Screen>
<Stack.Screen name="Error">{error}</Stack.Screen>
</Stack.Navigator>
);
};
【讨论】: