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
相关产品推荐
相关产品推荐

