reactjs 类型'组件类型〈{}>|无法将“ReactNode”赋给类型“ReactNode”

e5nszbig  于 2022-12-12  发布在  React
关注(0)|答案(1)|浏览(1167)

我想不出是什么错误。我已经看过这里了,它们似乎都不起作用。
应用程序

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'.

ssgvzors

ssgvzors1#

只需在界面中更改子对象的类型:

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;

因为React.ReactNode包含不同的类型:

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

相关问题