我正在尝试编写一个通用的React组件,该组件需要两种类型(IFoo
或IBar
)中的一种的道具,以及一个接受所选类型的道具的组件。
以下内容为何无效?
import React from 'react';
interface IFoo {
x: string;
}
interface IBar {
x: number;
}
const foo: React.FunctionComponent<IFoo> = (props: IFoo) => {
console.log("hello from foo!");
return <div>foo</div>
};
const bar: React.FunctionComponent<IBar> = (props: IBar) => {
console.log("hello from bar!");
return <div>bar</div>
};
interface IProps<T> {
props: T[];
Component: React.FunctionComponent<T>;
}
class HigherOrderComponent<T extends IBar | IFoo> extends React.Component<IProps<T>> {
render() {
const { props, Component } = this.props;
return (<div>
{props.map(prop => <Component {...prop}/>)};
</div>)
}
}
这将返回以下错误:
Type 'T' is not assignable to type 'IntrinsicAttributes & T & { children?: ReactNode; }'.
Type 'IFoo | IBar' is not assignable to type 'IntrinsicAttributes & T & { children?: ReactNode; }'.
Type 'IFoo' is not assignable to type 'IntrinsicAttributes & T & { children?: ReactNode; }'.
Type 'IFoo' is not assignable to type 'T'.
'IFoo' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'IFoo | IBar'.
Type 'T' is not assignable to type 'IntrinsicAttributes'.
Type 'IFoo | IBar' is not assignable to type 'IntrinsicAttributes'.
Type 'IFoo' has no properties in common with type 'IntrinsicAttributes'.(2322)
答案 0 :(得分:2)
快速解决方案是添加:
{props.map((prop: T & {}) => <Component {...prop}/>)};
我认为问题出在传播算子和联合类型(如果只有一种类型,它可以正常工作)。我知道TS在此之前有问题((
希望这会有所帮助:)
答案 1 :(得分:1)
您需要动态创建HOC类,以便包装Component并为其正确键入
import React from 'react';
interface IFoo {
x: string;
}
interface IBar {
x: number;
}
const foo: React.FunctionComponent<IFoo> = (props: IFoo) => {
console.log("hello from foo!");
return <div>foo</div>
};
const bar: React.FunctionComponent<IBar> = (props: IBar) => {
console.log("hello from bar!");
return <div>bar</div>
};
function createHOC<P extends IFoo | IBar>(Component: React.ComponentType<P>) {
return class HigherOrderComponent extends React.Component<P> {
render() {
console.log(this.props.x)
return <Component {...this.props} />
}
}
}
const WrapperFooComponent = createHOC(foo)
const WrapperBarComponent = createHOC(bar)
希望对您有帮助<3