【问题标题】:Default values for higher order components in ReactReact 中高阶组件的默认值
【发布时间】:2019-08-28 08:29:35
【问题描述】:

假设我有一个高阶组件:

interface MyHOCInterface { title: string }

export function wrapMyHoc<T extends MyHOCInterface>(
  Component: React.ComponentType<T>,) {
  return class extends React.Component<T> {
    state = {...this.props,}
    const {title} = {...(this.props as T)}
    render() {
      return(
        <>
          {title}
          <Component {...this.props as T} />
        </>
      )
    }
  }
}

然后是我这样定义的一些组件:

export const MyFirstComponent = wrapMyHoc(
  (props: MyHocInterface) => (<></>)
)

export const MySecondComponent = wrapMyHoc(
  (props: MyHocInterface) => (<></>)
)

当然,这将允许我像下面那样渲染它们。我注意到这段代码(MySecondComponent 组件的所有实例总是具有相同的标题):

<>
  <MyFirstComponent title='my first title'/>
  <MySecondComponent title='my second title' />
  <MySecondComponent title='my second title' />
  <MySecondComponent title='my second title' />
</>

我将如何设置一个默认值,这样我就可以编写以下内容并且仍然以my second title 作为标题:

<> <MySecondComponent /> </>

【问题讨论】:

  • 我不懂 wrapMyHoc,你传递了 Component 并且从不使用它,你使用 title 但它从未定义过。
  • @HMR :更新了代码。我正在寻找一种方法来允许调用wrapMyHocone 类型始终具有默认值,并且所有其他类型都不必指定默认值。
  • if Component of type MySecondComponent props.title = "my second title" 之类的东西(显然不是工作代码)
  • @HMR:好像有什么东西会进入 HOC。我不想碰我的 HOC
  • 如果传递的组件是 MySecondComponent 并且标题未定义,您能否包装 HOC 并为 title 设置默认值?您不能在 MySecondComponent 中为其设置默认值,因为 HOC 返回的类也在某处使用了标题?

标签: reactjs typescript higher-order-functions higher-order-components


【解决方案1】:

根据您对 MySecondComponent 使用另一个 HOC 的最后评论,我认为您可以这样做:

const doubeWrappedHOC = Component => {
  const HOC = wrapMyHoc(Component);
  return props =>
    props.title === undefined &&
    Component === MySecondComponent
      ? HOC({ ...props, title: defaultValue })
      : HOC(props);
};

它不在 TypeScript 中,MySecondComponent 必须在范围内/已导入,但您的所有组件都可以使用此 HOC,而不是仅将另一个 HOC 用于 MyCompnent。如果您想使用不同的 HOC 创建 MyCompnent,则可以省略 &amp;&amp; Component === MySecondComponent。再次使用逻辑wrapMyHoc 并为标题设置默认值。

【讨论】:

    猜你喜欢
    • 2018-04-03
    • 2017-11-03
    • 2019-02-20
    • 2019-06-26
    • 2021-03-25
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 2019-04-01
    相关资源
    最近更新 更多