简体   繁体   中英

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? Please help

As @adiga pointed out, interfaces determine the shape that values have. When using TypeScript with React, you may type your state and props with an interface.

An example using class components (see also this answer):

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). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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