我使用 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;
};
但是,这个函数返回的注解总是[]
!我假设这是因为我只是访问注解 setter / getter 接口(interface),而不是实际运行注解创建器。但是我无法弄清楚注释实际上是如何正常工作的。
我查看了 Creating a Syntax Highlighter for Ace 上的文档,但不明白网络 worker 是否/为什么需要参与此处。
谢谢!
最佳答案
这行不通,因为 editSession 使用 web worker 生成异步注释:
editSession.on('changeAnnotation', () => {
let annotations = editSession.getAnnotations();
callback(null, annotations)
});
请注意,目前每个 editSession 都会创建一个新的 worker,因此最好在现有的 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);
});
});
};
关于javascript - 如何在不实例化 Ace 编辑器实例的情况下使用 Ace 编辑器验证器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55352758/