【问题标题】:Is it possible to type a React component Props using a class property decorator?是否可以使用类属性装饰器键入 React 组件 Props?
【发布时间】:2020-07-05 18:40:02
【问题描述】:

我想要实现的是与 Angular 中的 @Input 的工作方式类似的事情(并且没有将接口/类型指定为泛型)。例如

class App extends React.Component {
 
 @Prop color: string;

}

当我使用带有 JSX 语法的组件时,是否可以为 TypeScript 创建这样的装饰器以从中推断 proptype 并提供类型断言?

【问题讨论】:

  • 是的,您可以通过键入组件接收的道具来做到这一点。type AppProps = {a:number} class App extends React.Component<AppProps, {}>

标签: reactjs typescript typescript-decorator


【解决方案1】:

不,这不可能。

如果你使用的是打字稿,你可以这样做:

interface Props {
  color: string;
}
class App extends React.Component<Props> {

}

【讨论】:

    【解决方案2】:

    通过使用react function componentshooks,您可以避免继承带有类型参数的 React.Component 类来为您的道具提供类型

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-09
      • 2018-12-03
      • 2019-12-28
      • 2020-02-03
      • 1970-01-01
      • 2017-02-04
      • 2019-08-08
      • 1970-01-01
      相关资源
      最近更新 更多