使用react-mentions时选中选项无法高亮显示的问题求助
React Mentions 选中提及内容后视图不高亮的解决办法
问题说明
使用react-mentions包时,用户选中建议选项后,内容能正常存入textarea的value,但视图中提及内容(比如Jack)不会高亮显示。
原有代码片段
组件代码
const list = [ { id: 'jack', display: 'Jack', }, { id: 'john', display: 'john', }, ] const TweetField = ({ text, setText }) => { return ( <> <Box> <MentionsInput value={text} onChange={(e) => setText(e.target.value)} style={tweetFieldStyle} a11ySuggestionsListLabel="What's happened?" > <Mention trigger='@' data={list} markup='@[__display__](__id__)' renderSuggestion={(user) => { console.log(user) return ( <div> {user.display} {user.id} </div> // <UserListItem {...user} key={user._id} onClick={() => {}} /> ) }} /> </MentionsInput> </Box> </> ) }
样式代码
export default { input: { backgroundColor: '#121212', color: '#FFF', minHeight: '32px', outline: 'none', width: '100%', borderRadius: '6px 6px 0 6px', border: `none`, fontSize: 18, display: 'block', lineHeight: 1.5, }, suggestions: { list: { backgroundColor: '#555', border: '1px solid rgba(0,0,0,0.15)', fontSize: 14, }, item: { padding: '5px 15px', borderBottom: '1px solid rgba(0,0,0,0.15)', '&focused': { backgroundColor: '#cee4e5', }, }, }, }
解决步骤
1. 修正onChange事件取值方式
react-mentions的onChange回调直接返回处理后的文本值,而非DOM事件对象。之前用e.target.value会导致状态同步异常,影响高亮渲染。
修改后的组件代码:
const TweetField = ({ text, setText }) => { return ( <> <Box> <MentionsInput value={text} onChange={(value) => setText(value)} // 直接使用返回的文本值 style={tweetFieldStyle} a11ySuggestionsListLabel="What's happened?" > <Mention trigger='@' data={list} markup='@[__display__](__id__)' renderSuggestion={(user) => { return ( <div key={user.id}> {/* 添加唯一key避免React警告 */} {user.display} {user.id} </div> ) }} /> </MentionsInput> </Box> </> ) }
2. 添加提及内容高亮样式
react-mentions会为高亮的提及元素自动添加mention类名,需在样式中定义该类的样式才能显示高亮效果。
更新后的样式代码:
export default { input: { backgroundColor: '#121212', color: '#FFF', minHeight: '32px', outline: 'none', width: '100%', borderRadius: '6px 6px 0 6px', border: `none`, fontSize: 18, display: 'block', lineHeight: 1.5, }, // 新增提及高亮样式 mention: { backgroundColor: '#1DA1F2', color: '#FFFFFF', padding: '2px 4px', borderRadius: '3px', }, suggestions: { list: { backgroundColor: '#555', border: '1px solid rgba(0,0,0,0.15)', fontSize: 14, }, item: { padding: '5px 15px', borderBottom: '1px solid rgba(0,0,0,0.15)', '&focused': { backgroundColor: '#cee4e5', }, }, }, }
3. 确认markup格式正确性
当前使用的markup='@[__display__](__id__)'符合react-mentions的解析规则,无需修改,只要状态和样式到位,就能正常解析并高亮提及内容。
内容的提问来源于stack exchange,提问作者Ram Farid
相关产品推荐
相关产品推荐

