[英]How to pass higher order component to React Navigation?
How to pass HOC to React Navigation?如何将 HOC 传递给 React Navigation? I want to wrap component by
SafeArea
.我想用
SafeArea
包装组件。 Below example throws an error:下面的示例引发错误:
Functions are not valid as React child.
函数作为 React 子级无效。 This may happen if you return Component instead of...
如果您返回 Component 而不是...
function withSafeArea(component: ComponentType) {
return function WithSafeArea() {
return <SafeArea>{component}</SafeArea>
}
}
<Stack.Screen
name={Routes.Introduction}
component={withSafeArea(Introduction)}
/>
//edit response for @Dreew Rese //编辑@Dreew Rese的响应
code causing error from comment导致注释错误的代码
// imports
function withSafeArea(component: ComponentType) {
return function WithSafeArea() {
return <SafeArea>{component}</SafeArea>
}
}
const Stack = createStackNavigator()
export const Content = () => {
const { authenticated } = useAuthentication()
if (authenticated) {
const IntroductionWithSafeArea = withSafeArea(Introduction)
return (
<AuthorizedContentProvider>
<WithNavigation>
<Stack.Screen
name={Routes.Introduction}
component={IntroductionWithSafeArea}
/>
<Stack.Screen name={Routes.Home} component={Home} />
<Stack.Screen name={Routes.NewEvent} component={NewEvent} />
</WithNavigation>
</AuthorizedContentProvider>
)
}
return (
<WithNavigation>
<Stack.Screen name={Routes.Sign} component={Sign} />
</WithNavigation>
)
}
This likely is because higher order components are really just higher order functions.这可能是因为高阶组件实际上只是高阶函数。 They just happen to consume React components and return decorated React components.
它们只是碰巧消费了 React 组件并返回了经过修饰的 React 组件。 Logically what you've done makes sense, but from React's perspective
withSafeArea
isn't a valid React component.从逻辑上讲,您所做的事情是有道理的,但从 React 的角度来看
withSafeArea
不是有效的 React 组件。
For these situations you usually will decorate the component when it is exported.对于这些情况,您通常会在导出组件时对其进行装饰。 Something like:
就像是:
export default withSafeArea(Introduction)
But occasionally you need to decorate components "on-the-fly", like when mapping dynamic content.但有时您需要“即时”装饰组件,例如在映射动态内容时。 Here you will need to instantiate a wrapped/decorated component just ahead of returning the JSX:
在这里,您需要在返回 JSX 之前实例化一个包装/装饰的组件:
const IntroductionWithSafeArea = withSafeArea(Introduction);
...
<Stack.Screen
name={Routes.Introduction}
component={IntroductionWithSafeArea}
/>
Additionally, you may want to tweak your HOC so it functions a bit more correctly, namely, you want any props passed to it to be passed on to the wrapped component.此外,您可能希望调整您的 HOC,使其功能更正确,即您希望传递给它的任何道具都传递给包装的组件。
function withSafeArea(Component: ComponentType) {
return function WithSafeArea(props) { // <-- accept props
return (
<SafeArea>
<Component {...props} /> // <-- pass props on
</SafeArea>
);
}
}
Slightly more succinct简洁一些
const withSafeArea = (Component: ComponentType) => props => (
<SafeArea>
<Component {...props} />
</SafeArea>
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.