Введите 'ComponentType<{}> | 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'.

🤔 А знаете ли вы, что...
JavaScript является одним из трех основных языков веб-разработки, вместе с HTML и CSS.


97
1

Ответ:

Решено

Просто измените тип дочерних элементов в вашем интерфейсе:

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