Ace Editor/React Ace能否通过绝对起止索引替代行列位置设置markers
AceEditor markers 配置相关解答
- 官方原生的
markers参数不直接支持传入子字符串绝对起止索引的配置方式,原生规则要求必须传入{startRow, startCol, endRow, endCol}格式的行列位置参数,也就是你示例中使用的配置结构。 - 如果要基于字符串绝对索引实现高亮,可以自行实现位置转换逻辑:先获取编辑器的完整文本内容,将目标片段的绝对起止索引换算为对应的行列坐标,再组装成符合要求的markers配置传入即可。
参考转换实现代码:
// 字符串绝对索引转对应行列坐标 const convertIndexToPos = (fullText, absoluteIndex) => { const prevContent = fullText.slice(0, absoluteIndex); const row = prevContent.split('\n').length - 1; const col = absoluteIndex - (prevContent.lastIndexOf('\n') + 1); return { row, col }; }; // 基于起止索引生成符合要求的marker配置 const createMarkerByIndex = (fullText, startIdx, endIdx, className) => { const startPos = convertIndexToPos(fullText, startIdx); const endPos = convertIndexToPos(fullText, endIdx); return { startRow: startPos.row, startCol: startPos.col, endRow: endPos.row, endCol: endPos.col, type: 'text', className }; };
注意:如果编辑器内容支持动态编辑,每次内容变更后需要重新根据最新文本计算坐标、更新markers配置,否则会出现高亮位置错位的问题。
官方标准行列坐标配置markers的示例代码如下:
const markers = [ { startRow: 3, startCol: 10, endRow: 3, endCol: 15, type: 'text', className: 'test-marker', }, { startRow: 6, startCol: 13, endRow: 6, endCol: 19, type: 'text', className: 'test-marker', }, ]; const wrapper = <AceEditor markers={markers} />;
内容的提问来源于stack exchange,提问作者Smarajit
相关产品推荐
相关产品推荐

