简体   繁体   中英

What is the correct way to type a React component class that has no props?

The top level component in a React project by definition won't have any props passed to it. What is the appropriate way to type this when using Typescript?

I've been using the following as a model recently, but perhaps there's a simpler way?

interface AppState {
    ...
}
class App extends React.Component<{},AppState> {
    constructor(props: never) {
        super(props);
        this.state = {
            ...
        }
        ...
    }
    ...
}

Constructors were mainly used to declare your state or bind your class methods. Nowadays, constructor is called implicitly if you omit it, no declaration needed. Hence once you omit it, it may lead you to wonder how to bind or declare state.

You can declare outside you state property, and likewise you can bind your methods declaring them as arrow functions:

class App extends React.Component<{},AppState> {
    // state can be declared outside from constructor
    state: AppState = { name: '' }

    // arrow function avoid the need to bind
    onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
      this.setState({name: e.target.value})
    }
}

This way you can write a cleaner syntax when using Class based Component.

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