簡體   English   中英

在React中導出接口Props的目的是什么(Typescript ver)

[英]What is the purpose of export interface Props in React (Typescript ver)

React Typescript Starter示例的Create a component部分中, Create a component,Typescript中有一個基本的React組件:

// src/components/Hello.tsx

import * as React from 'react';

export interface Props {
  name: string;
  enthusiasmLevel?: number;
}

function Hello({ name, enthusiasmLevel = 1 }: Props) {
  if (enthusiasmLevel <= 0) {
    throw new Error('You could be a little more enthusiastic. :D');
  }

  return (
    <div className="hello">
      <div className="greeting">
        Hello {name + getExclamationMarks(enthusiasmLevel)}
      </div>
    </div>
  );
}

export default Hello;

// helpers

function getExclamationMarks(numChars: number) {
  return Array(numChars + 1).join('!');
}

我是Typescript的新手。 Typescript似乎使用了Props接口來進行props類型檢查(類似於Proptypes npm包所做的事情 )。 所以問題是:

  1. 如果我已經使用了這種Typescript接口語法來進行道具類型檢查,是否仍需要在同一組件中使用像這樣的Proptypes包?
    import PropTypes from 'prop-types';

    Hello.propTypes = {
      name: PropTypes.string,
      enthusiasmLevel: PropTypes.number
    };
  1. 另外,為什么這里要使用導出界面? 導出接口道具的目的是什么? 是強制性的嗎?

首先,我建議以ES6方式聲明您的組件

const Hello: React.FC<IHello> = ({ name, enthusiasmLevel = 1 }) => {}

您的界面定義了組件的合同/可接受的參數

export interface IHello {
  name: string;
  enthusiasmLevel?: number;
}

您正在導出此文件,因此可以從其他要使用Hello組件的文件/組件中導入界面。 例如,您可以像其他組件一樣使用Hello組件:

const props: IHello = {
    name: "John",
    enthusiamsLevel: 5
}

<Hello {...props} />

如果我已經在使用這種Typescript接口語法來進行道具類型檢查,是否還需要在同一組件中使用道具類型?

您始終希望在TypeScript中輸入強類型定義。 因此,當在另一個組件中聲明prop變量時,您不想執行const props: any = {如果您以后決定更改此組件的接口聲明,則將被迫更新所有使用此接口的引用。 。 -您可能需要再增加1個prop變量,在這種情況下,您需要更新此接口的用法。 如果您不習慣TypeScript,一開始看起來似乎很丑陋-但是隨着時間的流逝,始終擁有強類型定義的好處就會顯現出來。 尤其是在更新類型定義時。

暫無
暫無

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

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