简体   繁体   English

对 React 中如何使用接口(TypeScript)感到困惑

[英]Confusion with how interface (TypeScript) is used in React

I am new to TypeScript in React and was learning how to properly integrate TypeScript into React project and got stuck with Interface, that is, why do we need to use interface in React?我是 React 中 TypeScript 的新手,正在学习如何将 TypeScript 正确集成到 React 项目中,并被接口卡住了,也就是说,为什么我们需要在 React 中使用接口? Please help请帮忙

As @adiga pointed out, interfaces determine the shape that values have.正如@adiga 指出的那样,接口决定了值的形状。 When using TypeScript with React, you may type your state and props with an interface.将 TypeScript 与 React 一起使用时,您可以键入 state 和带有接口的道具。

An example using class components (see also this answer):使用 class 组件的示例(另请参阅答案):

interface MyProps {}

interface MyState {
    foo: string;
    bar?: boolean;
}

class MyComponent extends React.Component <MyProps, MyState>  {
    constructor(props) {
        super(props);

        this.state = {
            // populate state fields according to props fields
        };
    }

    render() {
        ...
    }
}

An example using functional components:使用功能组件的示例:

  function MyForm(props: myProps) {
      ...
  }

As this Medium article points out, typing your state and props may help keep track of the shape of your state and props (and prevent errors).正如这篇Medium 文章所指出的,输入 state 和道具可能有助于跟踪 state 和道具的形状(并防止错误)。 You may for instance decide to define all your interfaces in a single file (eg. src/types/index.tsx ) and import your interfaces in your component files.例如,您可能决定在单个文件中定义所有接口(例如src/types/index.tsx )并将接口导入组件文件中。

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

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