react文本标注实现
React 文本标注实现方法
使用 contentEditable 实现基础标注
通过设置 contentEditable 属性使元素可编辑,结合 window.getSelection() 获取选中文本范围。利用 Range API 动态包裹选中文本:
const HighlightableText = () => {
const handleMouseUp = () => {
const selection = window.getSelection();
if (selection.toString().length > 0) {
const range = selection.getRangeAt(0);
const span = document.createElement('span');
span.className = 'highlight';
range.surroundContents(span);
}
};
return (
<div
contentEditable
onMouseUp={handleMouseUp}
dangerouslySetInnerHTML={{ __html: '可编辑的文本内容' }}
/>
);
};
使用第三方库(如 Draft.js) Draft.js 提供更完整的文本编辑与标注解决方案,支持复杂样式和实体管理:

import { Editor, EditorState, RichUtils } from 'draft-js';
const TextEditor = () => {
const [editorState, setEditorState] = useState(EditorState.createEmpty());
const handleKeyCommand = (command) => {
const newState = RichUtils.handleKeyCommand(editorState, command);
if (newState) {
setEditorState(newState);
return 'handled';
}
return 'not-handled';
};
const toggleHighlight = () => {
setEditorState(RichUtils.toggleInlineStyle(editorState, 'HIGHLIGHT'));
};
return (
<div>
<button onClick={toggleHighlight}>高亮文本</button>
<Editor
editorState={editorState}
handleKeyCommand={handleKeyCommand}
onChange={setEditorState}
/>
</div>
);
};
实现持久化标注 结合状态管理保存标注位置信息,使用字符偏移量记录标注范围:

const persistHighlight = (text, start, end) => {
const before = text.substring(0, start);
const highlighted = text.substring(start, end);
const after = text.substring(end);
return `${before}<span class="highlight">${highlighted}</span>${after}`;
};
标注样式与交互增强 通过 CSS 自定义标注样式并添加交互事件:
.highlight {
background-color: yellow;
cursor: pointer;
transition: background-color 0.3s;
}
.highlight:hover {
background-color: orange;
}
注意事项
- 跨浏览器兼容性需测试
Selection和RangeAPI - 长文本性能优化建议使用虚拟滚动
- 富文本场景推荐使用专业库如 Slate.js 或 TipTap
- 服务端渲染需处理
document未定义的情况






