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
。再次使用logicwrapMyHoc
,只为标题设置默认值。我不理解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);
};