我使用react-ace
在我的 React 应用程序中创建一个 CSS 文本编辑器。
这看起来像...
import Ace from 'react-ace'
...
<Ace
mode="css"
value={value}
onChange={onValueChange}
onValidate={onValidate}
...
/>
...
这工作得很好,而且很花哨 - 突出显示 CSS 语法错误和警告。此外,onValidate
返回错误/警告"注释"数据结构。
但是,在应用程序的其他地方,需要运行此 React Ace 组件中使用的相同验证器,但在此组件的上下文之外。本质上,我需要通过错误/警告注释系统传递value
内容,但无法实例化此 react 元素。
我尝试了以下方法:
import { EditSession } from 'brace'; # "brace" is the "module" compatible version of the ace editor that our "react-ace" uses
import 'brace/mode/css';
export const getCssAnnotations = (value)=> {
const editSession = new EditSession(value);
editSession.setMode('ace/mode/css');
const annotations = editSession.getAnnotations();
return annotations;
};
但是,此函数返回的注释始终[]
!我认为这是因为我只是在访问注释设置器/getter 界面,而不是实际运行注释创建器。但是我无法弄清楚注释实际上正常工作。
我已经查看了有关为 Ace 创建语法突出显示器的文档,但不明白是否/为什么需要 Web 工作者参与其中。
谢谢!
这是行不通的,因为 editSession 使用 web worker 生成异步的注释:
editSession.on('changeAnnotation', () => {
let annotations = editSession.getAnnotations();
callback(null, annotations)
});
文档
请注意,目前每个 editSession 都会创建一个新的工作线程,因此最好在 editSession 的现有实例上使用 setValue,或者在调用回调之前调用 editSession.destroy()
因此,完整的解决方案可能如下所示:
const getAnnotationsPromise = (value, mode)=> {
const editSession = new EditSession(value);
editSession.setMode(`ace/mode/${mode}`);
return new Promise((resolve)=> {
editSession.on('changeAnnotation', () => {
const annotations = editSession.getAnnotations();
editSession.removeAllListeners('changeAnnotation');
editSession.destroy();
resolve(annotations);
});
});
};