簡體   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