繁体   English   中英

如何使用属性指定组件的打字稿类型

[英]How to specify typescript type of a component with properties

我有一个组件SampleComponent.tsx

import React from 'react';

type Props = { text: string };

export const SampleComponent: React.FC<Props> = ({text})=><div>{text}</div>;

SampleComponent.variant1 = ({text})=><div>{'variant1' + text}</div>;

当我尝试在其他组件中使用SampleComponent.variant1时,出现打字稿错误:

Property 'variant1' does not exist on type ...

现在我只是使用as类型转换,但我认为有更好的方法。

我怎样才能解决这个问题?

编辑:如果我有动态变体,如何输入 - 从 1 到 4 这样 - .variant1 , .variant2 , .variant3.variant4

由于您已经说过 Sample Component 是一个 FC,因此 react 不会让您添加任何不属于 FC 的属性。 您可以扩展您将 SampleComponent 声明为的类型,如下所示:

export const SampleComponent: React.FC<Props> & {
  variant1: React.FC;
} = ({ text }) => <div>{text}</div>;

SampleComponent.variant1 = ({ text }) => <div>{"variant1" + text}</div>;

或者你可以为 props 提供类型,然后让 typescript 通过你使用它的方式找出其余的:

const SampleComponent = ({ text }: Props) => <div>{text}</div>;

SampleComponent.variant1 = ({ text }: Props) => <div>{"variant1" + text}</div>;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM