typescript 错误 TS2314:通用类型“组件<P,S>”需要 2 个类型参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32506180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:05:29  来源:igfitidea点击:

error TS2314: Generic type 'Component<P, S>' requires 2 type argument(s)

reactjstypescript

提问by bjfletcher

In using ReactJS with TypeScript, this error comes up:

在 TypeScript 中使用 ReactJS 时,出现此错误:

error TS2314: Generic type 'Component<P, S>' requires 2 type argument(s).

error TS2314: Generic type 'Component<P, S>' requires 2 type argument(s).

How do I fix this?

我该如何解决?

回答by bjfletcher

The Pis the props type and the Sis the state type. You'll want to change:

P是道具类型和S是状态型。你会想要改变:

class MyComponent extends React.Component { ...

class MyComponent extends React.Component { ...

to:

到:

interface MyProps {}
interface MyState {}

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

Then expand the MyPropsand MyStateinterfaces to include typing for all the props and state that the component needs.

然后扩展MyPropsMyState接口以包括输入组件所需的所有道具和状态。