【问题标题】:How do I wrap this child in an Higher Order Component?如何将此子组件包装在高阶组件中?
【发布时间】:2020-02-01 05:33:54
【问题描述】:
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 
}

我的&lt;AuthRequired&gt; 视图工作正常,但我的withAuth 却不行。

【问题讨论】:

    标签: reactjs react-native higher-order-components


    【解决方案1】:

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

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

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

    请看一下这个链接:Functions are not valid as a React child. This may happen if you return a Component instead of from render

    【讨论】:

      【解决方案2】:

      HOC 接受一个组件并返回另一个组件。您正在获取一个组件并返回一个 React 节点,而不是一个组件。 Docs reference

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

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

      这可能更容易理解为:

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

      【讨论】:

        【解决方案3】:

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

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

        然后用 Aux 包裹withAuth

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多