【发布时间】:2020-01-25 17:52:49
【问题描述】:
我正在尝试编写一个通用的 React 组件,它需要两种类型(IFoo 或 IBar)之一的 props 和一个接受所选类型的 props 的组件。
为什么以下不起作用?
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)
【问题讨论】:
标签: reactjs typescript higher-order-components