简体   繁体   English

键入没有道具的 React 组件 class 的正确方法是什么?

[英]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.根据定义,React 项目中的顶级组件不会传递任何 props。 What is the appropriate way to type this when using Typescript?使用 Typescript 时,正确的输入方式是什么?

I've been using the following as a model recently, but perhaps there's a simpler way?我最近一直在使用以下 model,但也许有更简单的方法?

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.构造函数主要用于声明您的state或绑定您的 class 方法。 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.因此,一旦省略它,您可能会想知道如何绑定或声明 state。

You can declare outside you state property, and likewise you can bind your methods declaring them as arrow functions:您可以在 state 属性之外声明,同样您可以绑定您的方法,将它们声明为箭头函数:

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.这样您就可以在使用基于 Class 的组件时编写更清晰的语法。

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

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