如何通过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
相关产品推荐
相关产品推荐

