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

时间:2019-10-07 19:37:53

标签: reactjs higher-order-components

我的代码类似于以下内容:

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

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

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

如何正确编写此文字,以便能够传递道具?我想我可能还需要在这里使用children,但不确定。

4 个答案:

答案 0 :(得分:2)

高阶组件将返回另一个组件(在这种情况下为另一个函数)。组件是返回JSX的函数。

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

答案 1 :(得分:2)

就是这样。

const HOC = (WrappedComponent) => {

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

答案 2 :(得分:2)

HOC是一个函数,它返回一个Component,通常会在其上注入一些props。您应该分开关注。实际的HOC应该看起来像这样

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

像这样被叫

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

如果您也想合并任意props,请尝试将传递到props的{​​{1}}传播出去

Component

如果愿意,可以创建附加图层。

  • const withFoo = Wrapped =>{ return props =>{ return <Wrapped injectedProps='foo' {...props}/> } } <Component propsToBeSpreaded='bar' /> HOC中注入了一些道具
  • Container接受任意Container
  • props呈现Container

代码

children

像这样称呼

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

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

答案 3 :(得分:1)

您仍然可以将道具和要增强的组件一起传递(按照您认为是错误的原始方法),因为-

  

HOC并非React API的一部分。它们来自React的组成性质。

所以您的HOC用法是-

const EnhancedComponent = higherOrderComponent(WrappedComponent, anyProps);

注意事项:

  1. 您的HOC接受一个Component并返回一个Component(增强或不增强)

    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>
        );
    }
相关问题