Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs React中高阶组件的默认值_Reactjs_Typescript_Higher Order Functions_Higher Order Components - Fatal编程技术网

Reactjs React中高阶组件的默认值

Reactjs React中高阶组件的默认值,reactjs,typescript,higher-order-functions,higher-order-components,Reactjs,Typescript,Higher Order Functions,Higher Order Components,假设我有一个更高阶组件: interface MyHOCInterface { title: string } export function wrapMyHoc<T extends MyHOCInterface>( Component: React.ComponentType<T>,) { return class extends React.Component<T> { state = {...this.props,} const

假设我有一个更高阶组件:

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} />
        </>
      )
    }
  }
}
我如何设置一个默认值,这样我就可以编写以下内容,并且仍然将
我的第二个标题
作为标题:

<> <MySecondComponent /> </>

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

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

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

它不在TypeScript中,
MySecondComponent
必须在作用域/inported中,但您的所有组件都可以使用此HOC,而不是仅针对myComponent使用另一个HOC。如果要使用不同的HOC创建MyComponent,则可以省去
&&Component==MySecondComponent
。再次使用logic
wrapMyHoc
,只为标题设置默认值。

我不理解wrapMyHoc,您传递
组件
但从不使用它,您使用
标题
,但它从未定义。@HMR:更新了代码。我要寻找的只是一种方法,允许调用
wrapMyHoc
的类型始终具有默认值,并且所有其他类型不必指定默认值。类似于
if Component of type MySecondComponent props.title=“my second title”
(显然不是工作代码)@HMR:看起来好像有什么东西会进入HOC内部。我不想触碰我的HOC。如果传递的组件是
MySecondComponent
且标题未定义,是否可以包装HOC并为
title
设置默认值?您不能在
MySecondComponent
中为它设置默认值,因为HOC返回的类也在某处使用了标题,对吗?
const doubeWrappedHOC = Component => {
  const HOC = wrapMyHoc(Component);
  return props =>
    props.title === undefined &&
    Component === MySecondComponent
      ? HOC({ ...props, title: defaultValue })
      : HOC(props);
};