如何将此 child 包装在高阶组件中?

How do I wrap this child in an Higher Order Component?

const LoggedInView = (props) => <Text>You are logged in!</Text>
export default withAuth(LoggedInView)


const withAuth = (component) => <AuthRequired>{ component }</AuthRequired>


const AuthRequired = (props) => {
    const context = useContext(AuthContext)
    if(!context.auth){
        return (
            <View style={styles.container}>
               <Text>You need to login . Click here</Text>
            </View>
        )
    }
    return props.children 
}

我的 <AuthRequired> 视图工作正常,但我的 withAuth 不工作。

据我所知,您不能 return 在 React 中将函数作为子函数。你试试这个怎么样?

const LoggedInView = <div>You are logged in!</div>;

当我在笔记本电脑上尝试时,此代码有效。

请看一下这个link:

HOC 使用一个组件和 return 另一个组件。您正在获取一个组件并 returning 一个 React 节点,而不是一个组件。 Docs reference

对于您的情况,您应该能够执行以下操作:

const withAuth = (Component) => (props) => <AuthRequired><Component ...props /></AuthRequired>

可能更容易理解为:

function withAuth(Component) {
    return function WithAuthHOC(props) {
        return (
            <AuthRequired>
                <Component ...props />
            </AuthRequired>
        );
    }
}

您可以使用辅助组件。它是一个高阶组件。辅助元素是一些没有语义目的但存在的目的是分组元素,样式等。只需创建一个名为 Aux.js 的组件并将其放在上面:

const aux = ( props ) => props.children;

export default aux;

然后用 Aux.

包装 withAuth
const withAuth = (component) => {
     return ( 
           <Aux> 
               <AuthRequired>{ component }</AuthRequired>
           </Aux> 
      );
}