如何访问功能性 HOC 中的道具?

How to access props in a functional HOC?

我有类似下面的代码:

const HOC = (props, WrappedComponent) => {
    return (
       <>
          <WrappedComponent />
          <Icon className="props.iconStyles" />
       </>
     );
};

这实际上不是有效代码,但您可以看到我正在努力完成的工作。我希望能够通过以下方式使用它:

<HOC iconStyles="icon-stuff">
    <TheComponentIWantToWrap>
</HOC>

这个怎么写才正确,才能让props通过呢?我想我可能也需要在这里使用 children,不确定。

高阶组件将 return 另一个组件(在本例中为另一个函数)。组件是 returns JSX 的函数。

const HOC = (Component) => {
  return function WrappedComponent(props) {
    return (
       <>
          <Component {...props} />
          <Icon className="props.iconStyles" />
       </>
     );
  };
};

应该是这样的。

const HOC = (WrappedComponent) => {

  const MyComponent = props => {
    return (
       <>
          <WrappedComponent {...props} />
          <Icon className={props.iconStyles} />
       </>
     );
   }
   
  return MyComponent;
};

一个HOC是一个returns一个Component的函数,通常在它上面注入一些props。你应该分开关注点。实际的 HOC 应该是这样的

const withFoo = Component =>{
    return props =>{
        return <Component injectedProps='foo' />
    }
}

然后这样称呼

const Component = withFoo(({ injectedProps }) =>{
    return <jsx />
})

如果你想合并任意 props 以及尝试传播传递给 Component

props
const withFoo = Wrapped =>{
    return props =>{
        return <Wrapped injectedProps='foo' {...props}/>
    }
}

<Component propsToBeSpreaded='bar' />

如果您愿意,可以创建一个附加层。

  • HOCContainer
  • 中注入一些道具
  • Container 接受任意 props
  • Container 渲染 children

密码

   const withHoc = Container =>{
        return () => <Container injected='foo' />
    }

    const Container = withHoc(({ children, injected, ...aditionalProps}) =>{
         return(
             <div {...aditionalProps}>
                 { children }
             </div>
         )
    })

然后这样称呼它

const FinalComp = () =>{
    return <Container foo='foo'> <span /> </Container>
}

您仍然可以传递道具和要增强的组件(根据您认为错误的原始方法)这是正确的,因为 -

HOCs are not part of React API. They emerge from React's nature of composition.

所以你的 HOC 用法是 -

const EnhancedComponent = higherOrderComponent(WrappedComponent, anyProps);

注意事项:

  1. 您的 HOC 包含一个组件和 returns 一个组件(增强或未增强)

    const higherOrderComponent = (WrappedComponent, anyProps) => {
        return class extends React.Component {
            // Component body
        }
    } 

  1. 不要改变原始组件。使用合成。
  2. 将不相关的属性传递给包装的组件。
    const higherOrderComponent = (WrappedComponent, anyProps) => {
        return class extends React.Component {
            render() {
                const { HOCProp, ...compProps } = this.props;
                return (
                    <WrappedComponent
                        ...compProps,
                        someProp={anyProps.someProp}
                    />
                );
            }
        }
    }

考虑到所有这些,您的 HOC 将如下所示 -

    const withWrappedIcon = (CompToWrap, iconStyle) => {
        return (
           <Icon className={iconStyle}>
              <CompToWrap />
           </Icon>
        );
    }