【发布时间】:2020-02-26 01:40:33
【问题描述】:
我想创建一个 React TypeScript 组件,其 props 是两个不同接口的联合。但是,当我这样做时,我会收到警告:
TS2339: Property 'color' does not exist on type 'PropsWithChildren<Props>'
如何创建一个结合两个不同 prop 接口的 React TypeScript 组件,同时能够解构这些 prop?谢谢!
sampleComponent.tsx:
import * as React from 'react';
interface SamplePropsOne {
name: string;
}
interface SamplePropsTwo {
color: string;
}
type Props = SamplePropsOne | SamplePropsTwo;
const SampleComponent: React.FC<Props> = ({ color, name }) => (
color ? (
<h1>{color}</h1>
) : (
<h1>{name}</h1>
)
);
export default SampleComponent;
【问题讨论】:
-
为什么你不想只将一种类型的道具从父组件传递给
SampleComponent?你可以通过<SampleComponent name={name} />或<SampleComponent name={color} />。 -
@AndriiGolubenko,请不要从字面上理解组件实现细节。问题更多是关于如何创建一个可以接受一系列不同prop接口的组件。
-
我知道您只是举了一个例子。但是您要创建的不是组件。它就像一个组件结构,接受类型、数据,然后呈现所需的组件。
标签: reactjs typescript