You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript报错:ComponentType<{}> | ReactNode无法赋值给ReactNode

解决TS2322类型不兼容错误

错误根源

你在CellProps中错误地将children的类型定义为React.ComponentType | string,但React组件的children默认类型是React.ReactNode。当你在App中传入字符串Hello时,TypeScript检测到类型不匹配——ComponentType是组件的引用类型(而非可渲染的节点),和ReactNode无法兼容,因此抛出TS2322错误。

解决方案

有两种可行的修复方式:

方案一:移除自定义的children类型声明

FunctionComponent已经内置了children: React.ReactNode的类型,无需手动声明:

import React, { FunctionComponent, useState } from "react";
import classes from "./Cell.module.css";

// 移除children的自定义定义,使用FunctionComponent默认的children类型
export type CellProps = {};

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;

方案二:修正children的类型为ReactNode(或精确的可渲染类型)

如果你需要明确声明children类型,应使用React.ReactNode(包含所有React可渲染的类型:字符串、元素、数组等),或者更精确的类型(比如string | React.ReactElement):

import React, { FunctionComponent, useState } from "react";
import classes from "./Cell.module.css";

export type CellProps = {
  // 使用ReactNode覆盖默认类型,或指定更精确的可渲染类型
  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.ComponentType用于表示组件本身(比如函数组件或类组件的引用),而非组件渲染后的节点。你的场景是需要渲染子节点(如字符串、元素),因此必须使用React.ReactNode这类可渲染节点的类型。

内容的提问来源于stack exchange,提问作者Koller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 16:15:41