我正在将React组件从JavaScript转换为TypeScript.该组件包括对React.cloneElement
的调用,传递通过组件props 接收的值.所讨论的值将是不同的react 组分,在下面的示例中称为Dep
.Dep
是一个基于类的组件,这就是它同时作为类型和值工作的原因).我得到了一个类型错误,我不知道如何解决.
下面是一个简化的示例,其中只包含演示错误所需的内容:
import React from "react";
import Dep from "./Dep";
export interface ExampleProps {
dep: Dep;
}
export const Example = (props: ExampleProps) => {
let dep = React.cloneElement(props.dep);
// ^~~~~~~~~ TS error here
return (
<div>
{dep}
</div>
);
};
以及编译器的错误:
src/components/Example.tsx:9:32 - error TS2769: No overload matches this call.
The last overload gave the following error.
Argument of type 'Dep' is not assignable to parameter of type 'ReactElement<unknown, string | JSXElementConstructor<any>>'.
Type 'Dep' is missing the following properties from type 'ReactElement<unknown, string | JSXElementConstructor<any>>': type, key
9 let dep = React.cloneElement(props.dep);
~~~~~~~~~
node_modules/@types/react/index.d.ts:331:14
331 function cloneElement<P>(
~~~~~~~~~~~~
The last overload is declared here.
Found 1 error.
我知道cloneElement
期望它的第一个参数是ReactElement
.我不清楚这种类型代表什么,为什么Dep
不兼容.以下是ReactElement
的定义,供参考:
interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>> {
type: T;
props: P;
key: Key | null;
}
错误消息说,它不兼容的原因是缺少type
和key
属性,但不清楚它为什么希望有这样的属性,以及我如何用这个形状表示我的组件.