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

ReactJS中如何在字符串文本内渲染span元素数组?

问题原因

你将React生成的span元素(本质为JS对象)直接放入模板字符串拼接,对象被隐式转换为字符串时就会输出[object Object]。只有直接将JSX对象/数组作为渲染值时,React才会将其解析为真实DOM元素。

解决方案

直接把静态文本和span元素组合成JSX结构即可,不需要拼接为字符串:

generateQuestion() {
    const newState = { ...this.state };
    // 注意map生成的列表元素需要加key属性避免React警告
    const numbers = newState.numbers.map((item, index) => 
        <span key={index} style={{color: "red"}}>{item.number}</span>
    )

    return (
        <div>
            Place the numbers {numbers[0]}, {numbers[1]} and {numbers[2]} in the right order.
        </div>
    );
}

如果数字数量不固定,可通过reduce方法动态拼接标点和元素,适配任意长度的数字数组:

generateQuestion() {
    const newState = { ...this.state };
    const numbers = newState.numbers.map((item, index) => 
        <span key={index} style={{color: "red"}}>{item.number}</span>
    )

    // 动态拼接标点,适配任意数量的数字
    const content = numbers.reduce((res, item, idx) => {
        if(idx === 0) return [item]
        if(idx === numbers.length - 1) return [...res, ' and ', item]
        return [...res, ', ', item]
    }, [])

    return (
        <div>
            Place the numbers {content} in the right order.
        </div>
    );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 05:06:02