【发布时间】: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 :更新了代码。我正在寻找一种方法来允许调用
wrapMyHoc的 one 类型始终具有默认值,并且所有其他类型都不必指定默认值。 -
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