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

如何通过map提取数组中React元素的子内容为字符串?

解决办法

你这里的item是个React元素对象,React元素的内部文本内容存在props.children属性里。如果每个item都是单纯的<div>文本</div>这种结构,直接取这个属性就行:

{list.map((sectionList) => (
  <SelectItem
    key={sectionList.id}
    value={sectionList.item.props.children}
  >
    {sectionList.item}
  </SelectItem>
))}

要是遇到复杂结构怎么办?

如果item里面不止纯文本(比如嵌套了其他元素、有多个子节点),可以写个小工具函数来递归提取纯文本:

// 提取React元素里的纯文本
const getPlainText = (element) => {
  if (typeof element === 'string') return element;
  if (Array.isArray(element)) {
    return element.map(getPlainText).join('');
  }
  if (element?.props?.children) {
    return getPlainText(element.props.children);
  }
  return '';
};

// 使用的时候
{list.map((sectionList) => (
  <SelectItem
    key={sectionList.id}
    value={getPlainText(sectionList.item)}
  >
    {sectionList.item}
  </SelectItem>
))}

更靠谱的优化建议

其实最好的方式是一开始就把文本单独存在数据里,别存React元素。比如把数组改成这样:

list: [
  {
    id: '1',
    text: 'First name',
    item: <div>First name</div>,
  },
  {
    id: '2',
    text: 'Last name',
    item: <div>Last name</div>,
  },
],

之后直接用sectionList.text当value,这比依赖React元素的内部结构要安全得多,后续维护也方便。

内容的提问来源于stack exchange,提问作者sir-haver

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 16:10:30