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

如何在React组件外部编写JSX并转换为ReactElement使用

可行实现方案

你描述的模式本身可以正常运行,无法生效大概率是类型定义错误和缺少依赖引入导致的,按以下步骤修正即可:

1. 修正constants.ts配置

如果是React 17以前的版本,必须手动引入React才能支持JSX语法,类型定义保持ReactElement即可:

// constants.ts
import React, { ReactElement } from 'react';

export interface ItemInfo {
  title: string;
  description: ReactElement;
}

export const DATA: ItemInfo[] = [
  {
    title: 'Foo',
    description: (
      <>
        <p>Some JSX.</p>
        <p>To be rendered in a React component.</p>
      </>
    ),
  },
  {
    title: 'Bar',
    description: (
      <>
        <p>More JSX.</p>
        <p>To be rendered in a React component.</p>
      </>
    ),
  },
];

2. 修正组件类型与语法

React.FC的泛型参数是组件接收的props对象的类型,不能直接传入数组类型,同时需要补充map渲染的key属性避免React警告:

// ItemComponent.tsx
import React, { FC } from 'react';
import { ItemInfo } from './constants';

const ItemComponent: FC<ItemInfo> = ({title, description}) => (
  <div>
    <h2>{title}</h2>
    <div>{description}</div>
  </div>
);

export default ItemComponent;
// ListComponent.tsx
import React, { FC } from 'react';
import { ItemInfo } from './constants';
import ItemComponent from './ItemComponent';

const ListComponent: FC<{ items: ItemInfo[] }> = ({ items }) => (
  <div>
    {items.map((item, index) => <ItemComponent key={index} {...item} />)}
  </div>
);

export default ListComponent;

该模式的适用场景与缺陷

适用场景

仅适合纯静态无动态依赖的配置场景,比如固定的帮助中心说明、功能介绍列表,确实可以实现配置与渲染逻辑分离,方便多业务侧复用同一份配置。

不建议使用的场景

  • 若description需要依赖运行时的动态参数(比如用户信息、组件内部state、主题变量等),常量中提前生成的JSX无法获取运行时上下文,会导致渲染异常
  • 常量中的JSX会在模块加载时就完成创建,即使对应组件没有渲染也会占用内存,配置量大时会拖慢首屏加载速度
  • 内容完全写死,无法适配国际化、动态内容下发这类需求

更灵活的替代方案

如果有动态参数需求,推荐将description改为返回JSX的函数形式:

调整类型定义

import React, { ReactElement } from 'react';

export interface ItemInfo {
  title: string;
  // 支持传入自定义参数
  description: (params?: Record<string, any>) => ReactElement;
}

常量配置写法

export const DATA: ItemInfo[] = [
  {
    title: 'Foo',
    // 改为函数形式,不会提前执行渲染,支持接收动态参数
    description: (params) => (
      <>
        <p>Hello {params?.userName || 'Guest'}</p>
        <p>To be rendered in a React component.</p>
      </>
    ),
  },
]

组件侧调用

const ItemComponent: FC<ItemInfo> = ({title, description}) => (
  <div>
    <h2>{title}</h2>
    {/* 调用函数,可传入组件内部的动态参数 */}
    <div>{description({ userName: '张三' })}</div>
  </div>
);

如果有动态内容下发、国际化需求,更推荐将description存为结构化数据(比如markdown格式、段落配置数组),单独写通用渲染组件解析内容,完全分离数据与渲染逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 14:18:04