我想知道在 Typescript 中指定 React 组件没有 props 的正确方法是什么。
如果我有一个组件,我可以通过两个接口(interface)指定 props 和 state 的内容:
interface MyProps {
text: string
}
interface MyState {
count: number
}
class MyComponent extends React.Component<MyProps, MyState> {
...
}
那么,如果我的组件没有 props,我应该使用 void
、undefined
还是 {}
?
最佳答案
Typescript 2.3 的公告中回答了这个(几乎)确切的问题.
However, much of the time, state is never used in a component. In those cases, we can just write the type as object or {}, but we have to do so explicitly:
class FooComponent extends React.Component<FooProps, object> { // ... }
因此在您的情况下,您只需将 object
的用法反转为 props 参数而不是 state 参数。
关于javascript - react 和 typescript : Convention for classes when no props are being passed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43833912/