React中如何为<span>内特定字符设置条件样式
解决React动态表单中下划线单独变色的问题
你当前的问题是给整个文本span设置了颜色,导致整段内容一起变色。要实现仅下划线单独变色,需要把文本拆分成普通内容和下划线两部分分别渲染,给下划线单独添加样式。
步骤1:编写文本格式化辅助函数
创建一个函数,将输入文本按下划线拆分,然后在拆分后的内容之间插入带指定颜色的下划线元素:
const formatQuestionText = (text) => { if (!text) return null; // 按下划线分割文本 const parts = text.split('_'); return parts.map((part, idx) => ( <React.Fragment key={idx}> {part} {/* 最后一段内容后不再添加下划线 */} {idx !== parts.length - 1 && <span style={{ color: '#E11F6E' }}>_</span>} </React.Fragment> )); };
步骤2:修改页面渲染逻辑
把原来直接渲染form.question的地方替换成调用上述函数,同时移除整个questionSpan的颜色判断(因为现在仅给下划线单独设置颜色):
修改后的核心渲染代码:
{isShown && <span className='questionSpan' style={{ color: 'black' }}> <span style={{fontWeight: 'bold'}}>{index+1})</span> {formatQuestionText(form.question)} </span>}
完整修改后的代码
<form onSubmit={submit}> {formFields.map((form, index) => { return ( <div key={index} className='tfRow'> <div className='tfClmnL'> {!isShown && <input name='question' className='questionInput' placeholder='Question' onChange={event => handleFormChange(event, index)} value={form.question} style={{marginLeft: '30px', width: '450px'}} /> } {isShown && <span className='questionSpan' style={{ color: 'black' }}> <span style={{fontWeight: 'bold'}}>{index+1})</span> {formatQuestionText(form.question)} </span>} </div> {!isShown && <button style={{marginRight: '0px'}}className='commandWhite cancel' alt='alternative' title='Remove Question' onClick={() => removeFields(index)}><img className='blackIcon' src={blackCancel}/></button>} </div> ) })} </form>
这个方案的逻辑很直接:通过split('_')把文本切割成不含下划线的片段,然后在每两个片段之间插入带红色样式的下划线span,这样就只有下划线会呈现指定颜色,其他内容保持默认黑色。
内容的提问来源于stack exchange,提问作者Ivan Arandia
相关产品推荐
相关产品推荐

