“ReactNode”不是有效的 JSX 元素

问题描述 投票:0回答:4

我有以下代码(codesandbox):

import { ComponentType, ReactNode } from "react";

type DatetimeCell = ({ value }: { value: string }) => ReactNode;

function getDateTimeCell(): DatetimeCell {
  return ({ value }) => value;
}

function buildCell({
  value
}: {
  value: string;
}): ComponentType<{ value: string }> {
  const DateTimeCell = getDateTimeCell();
  return ({ value }) => <DateTimeCell value={value} />;
}

返回时

buildCell
我收到错误:

'DateTimeCell' cannot be used as a JSX component.
  Its return type 'ReactNode' is not a valid JSX element.

我认为

ReactNode
将是有效 JSX 的最通用类型,但事实似乎并非如此。
为什么
ReactNode
不是有效的 JSX?我该如何解决这个问题?

编辑: 我知道将

value
包装在 React 片段中可以解决这个问题。然而,在这个特定的应用程序中,我需要类型
DatetimeCell
才能返回任何有效的 JSX。所以应该包括
string

reactjs typescript react-typescript
4个回答
10
投票

为什么 ReactNode 无效 JSX ?? => https://stackoverflow.com/a/72353143/10146901

我该如何解决这个问题? => 只需返回

JSX.Element
作为函数返回类型。

function buildCell({ value }: { value: string }): JSX.Element { // ... my codes }

您的codesandbox

的解决方案

0
投票

ReactNode
类型的一部分是
undefined
,我认为这不是一个有效的JSX元素。

解决问题的最简单方法就是输入

DatetimeCell
作为组件,并始终从
getDateTimeCell
返回一个元素 - 只需将结果包装在片段中即可。

import React, { ComponentType } from 'react';

type DatetimeCell = ComponentType<{ value: string }>;

function getDateTimeCell(): DatetimeCell {
  return ({ value }) => <>{value}</>;
}

function buildCell({ value }: { value: string }): ComponentType<{ value: string }> {
  const DateTimeCell = getDateTimeCell();
  return ({ value }) => <DateTimeCell value={value} />;
}

0
投票

我遇到了同样的问题,并通过将 TypeScript 版本更新到 5.4.2 来解决。这解决了问题。


-3
投票

当您调用 DateTimeCell 时,它期望返回一个 JSX 元素(ReactNode)。您当前在 getTimeCell 函数中返回一个字符串而不是 React 节点。我建议使用 React 提供的 FC 类型来输入功能组件,如下所示:

import { FC } from "react";

type Props = { value: string };
type DatetimeCell = FC<Props>;

function getDateTimeCell(): DatetimeCell {
  return ({ value }) => <>{value}</>;
}

function buildCell({ value }: Props): DatetimeCell {
  const DateTimeCell = getDateTimeCell();
  return ({ value }) => <DateTimeCell value={value} />;
}

buildCell({ value: "hello" });
© www.soinside.com 2019 - 2024. All rights reserved.