类型 '组件类型<{}> |ReactNode"不能分配给类型"ReactNode"



我不知道是什么错误。我已经看过这里了,好像没有一个可以用的。

应用

import React from "react";
import Cell from "./components/cell/Cell";
function App() {
return <Cell>Hello</Cell>;
}
export default App;

电池组件

import React, { FunctionComponent, useState } from "react";
import classes from "./Cell.module.css";
export type CellProps = {
children: React.ComponentType | string;
};
const Cell: FunctionComponent<CellProps> = (props) => {
const [isEditMode, setIsEditMode] = useState(false);
const changeLabelToInput = () => {
setIsEditMode(true);
};
return isEditMode ? (
<input />
) : (
<div onClick={changeLabelToInput}>{props.children}</div>
);
};
export default Cell;

如果我运行这个,我得到下一个错误:TS2322: Type 'ComponentType<{}> | ReactNode' is not assignable to type 'ReactNode'.

只要改变你的界面中的子元素的类型:

import React, { FunctionComponent, useState } from "react";
import classes from "./Cell.module.css";
export type CellProps = {
children: React.ReactNode;
};
const Cell: FunctionComponent<CellProps> = (props) => {
const [isEditMode, setIsEditMode] = useState(false);
const changeLabelToInput = () => {
setIsEditMode(true);
};
return isEditMode ? (
<input />
) : (
<div onClick={changeLabelToInput}>{props.children}</div>
);
};
export default Cell;

因为反应。ReactNode包含不同的类型:

type React.ReactNode = string | number | boolean | React.ReactElement<any, string | React.JSXElementConstructor<any>> | React.ReactFragment | React.ReactPortal | null | undefined

最新更新