javascript - react 和 typescript : Convention for classes when no props are being passed

标签 javascript reactjs typescript

我想知道在 Typescript 中指定 React 组件没有 props 的正确方法是什么。

如果我有一个组件,我可以通过两个接口(interface)指定 props 和 state 的内容:

interface MyProps {
  text: string
}

interface MyState {
  count: number
}

class MyComponent extends React.Component<MyProps, MyState> {
  ...
}

那么,如果我的组件没有 props,我应该使用 voidundefined 还是 {}

最佳答案

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/

相关文章:

javascript - 如何只加载一个div而不加载所有页面文件

javascript - 顶部 div 的动画位置创建空间

javascript - 如果发布请求成功则关闭对话框

javascript - 我的浏览器化脚本无法运行

node.js - 打字安装不适用于已配置的 typescript 定义

javascript - Node ,SSH2服务器等待输入

javascript - ExpressJS - 不会将新用户发布到 MongoDB(500 内部服务器错误)

javascript - React Native - setTimeout 循环内

typescript - 键入具有任意数量的不同参数的函数

typescript - 如何在 TypeScript 中初始化一个对象