[英]What is the correct way to type a React component class that has no props?
根据定义,React 项目中的顶级组件不会传递任何 props。 使用 Typescript 时,正确的输入方式是什么?
我最近一直在使用以下 model,但也许有更简单的方法?
interface AppState {
...
}
class App extends React.Component<{},AppState> {
constructor(props: never) {
super(props);
this.state = {
...
}
...
}
...
}
构造函数主要用于声明您的state
或绑定您的 class 方法。 现在,如果省略构造函数,它会被隐式调用,不需要声明。 因此,一旦省略它,您可能会想知道如何绑定或声明 state。
您可以在 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})
}
}
这样您就可以在使用基于 Class 的组件时编写更清晰的语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.