gpt4 book ai didi

reactjs - 当使用 React Component 作为参数时为 "Type is missing the following properties, context, setState"

转载 作者:行者123 更新时间:2023-12-03 13:43:46 26 4
gpt4 key购买 nike

我的用例非常简单,我想要一个动态 react 组件并将其保存在注册表中:

import { Component } from 'react';
import DummyComponent from './DummyComponent';

class Registry {
TestComponent: Component = DummyComponent;
}

DummyComponent.tsx:

import { Component } from 'react';

export default class DummyComponent extends Component {
constructor(props: any) {
super(props);
throw new Error('Cannot use this dummy component');
}
}

这会引发 TypeScript 错误:ts(2740): Type 'typeof DummyComponent' is missing the following properties from type 'Component<{}, {}, any>': context, setState, forceUpdate, render, and 3 more.

我做错了什么?我只要Registry.TestComponent要成为一个 React 组件,它不必具有所有这些属性,因为 React 组件不需要它们。

我做了一个StackBlitz example显示错误。错误略有不同,但我相信这是同一个问题。

tsconfig.json

{
"compilerOptions": {
"target": "es2015",
"jsx": "react",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"lib": ["esnext"],
"noEmit": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"strict": true
},
"include": ["src/**/*"]
}

最佳答案

Component类型是组件类的实例,而DummyComponent本身就是一个类。

应该是:

class Registry {
TestComponent: ComponentClass = DummyComponent;
}

如果 TestComponent 不限于类组件,它是:

class Registry {
TestComponent: ComponentType = DummyComponent;
}

关于reactjs - 当使用 React Component 作为参数时为 "Type is missing the following properties, context, setState",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54831133/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com