簡體   English   中英

如何正確使用 Typescript 中的 React 道具?

[英]How do I use React props in Typescript correctly?

我是 React 和 typescript 的新手。

我發現我需要這樣聲明道具:

const Title = ({title}:{[key:string]:any}) => {

但這對我來說似乎有點令人費解。 有沒有更好的方法來 go 關於這個?

如果需要,您可以通過聲明一個包含您期望的所有道具的接口來保持簡單:

interface MyProps {
  A: string;
  B: number;
  C?: number; // C is optional
}

const MyComponent = ({ A, B }: MyProps) =>  { ... }

我建議使用FC泛型(它是FunctionComponent泛型的別名)。 我更喜歡使用它而不是使用泛型,因為它附加了children屬性以及從功能組件React.Element vs JSX.Element中鍵入返回值。

import * as React from "react";
import {FC} from "react";

interface ITitleProps {
   title: string;
}

// This works as expected
export const Title1: FC<ITitleProps> = ({
    title,
    children // Added by 'FC'
}) => {
    return (
        <div>
            <h1>{title}</h1>
            <p>{children}</p>
        </div>
    );
};

// This produces an error
export const Title2 = ({
    title,
    children // property 'children' does not exist on type 'ITitleProps'
}: ITitleProps) => {
    return (
        <div>
            <h1>{title}</h1>
            <p>{children}</p>
        </div>
    );
};

這個 GitHub 在嘗試弄清楚如何將 TS 與 React 一起使用時非常寶貴: React TypeScript Cheatsheet

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM