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

React动态生成文本在Div中单词拆分,静态文本排版正常

动态生成文本单词被拆分问题

我从JSON文件随机生成文本块,使用静态文本时,Div右端若单词过长会自动换行;但使用动态生成的文本时,单词会被拆分。

React代码

<div className="test">
    <div className="box">
        <p className="word">
            {wordList.map((word, wordIndex) => {
                const typedWord = typedWords[wordIndex] || "";
                const isCurrentWord = wordIndex === typedWords.length;
                const hasWrongChars = typedWord.split("").some((char, index) => char !== word[index]);
                const isExcessLength = typedWord.length > word.length;
                const isIncomplete = typedWord.length >= 0 && typedWord.length < word.length && typedWords.includes(typedWord);
                const shouldHighlightWordRed = hasWrongChars || isExcessLength || isIncomplete;

                return (
                    <span key={wordIndex}>
                        {word.split("").map((char, charIndex) => {
                            let charColor = "#fff";

                            if (wordIndex < typedWords.length) {
                                charColor = shouldHighlightWordRed ? "red" : "green";
                            } else if (isCurrentWord) {
                                const typedChar = typedChars[charIndex] || "";
                                charColor = typedChar === char ? "green" : typedChar !== "" ? "red" : "#fff";
                            }

                            return (
                                <span key={charIndex} style={{ color: charColor }}>{char}</span>
                            );
                        })}
                        {'\u00A0'} // space after each word
                    </span>
                );
            })}
        </p>
    </div>

    <div style={{ display: "flex", justifyContent: 'row' }}>
        <input
            ref={inputRef}
            value={currentWord}
            onChange={handleInputChange}
        />
    </div>
</div>

CSS样式

.test {
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 62vh;
    padding-left: 20px;
    padding-right: 20px;
    max-width: 58rem;
    width: 58rem;
}

.box {
  font-size: 1.5rem;
  overflow: hidden;
  height: 149px;
  align-items: center;
  user-select: none;
  white-space: pre-wrap;
  overflow-wrap: break-word
}
.box .word {
  position: relative;
  margin: 0 5px 2px;
}
.box .word span {
color: var(--sub-color);
line-height: 2em;
font-weight: 100;
}

效果对比

  • 静态文本效果:排版正常,过长单词在Div右端自动换行,保持单词完整性
  • 动态文本效果:单词被拆分换行,无法保持完整单词显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 14:48:16