现有的两个答案都非常有助于我解决这个问题,但我仍然遇到了一些我必须解决的问题(一些显然是由于 api 的变化)。这是对我有用的两个答案的组合。
注意,例如,当您运行这些 sn-ps 或 jsFiddle 时,CORS 检查将阻止 worker 加载,仅仅因为示例“有效”并不意味着它会全部集成到您的项目中即可工作。
另请注意...这是使用钩子的反应代码,但应该应用基本代码。
它还使用来自Set width of ace editor instance according to the length of characters in it的调整大小代码
const editDiv = useRef<HTMLDivElement>(null);
useEffect(() => {
if (editing) {
if (!editor && editDiv.current) {
editDiv.current.textContent = value;
const ed = ace.edit(editDiv.current);
ed.setOptions({
maxLines: 1,
autoScrollEditorIntoView: true,
highlightActiveLine: false,
printMargin: false,
showGutter: false,
enableLiveAutocompletion: true,
enableBasicAutocompletion: true,
enableSnippets: false,
mode: "ace/mode/javascript",
theme: "ace/theme/tomorrow_night_eighties"
});
ed.commands.bindKey(
"Up|Ctrl-P|Down|Ctrl-N|PageUp|PageDown",
"null"
);
ed.commands.addCommand({
name: "SaveOnEnter",
bindKey: {
win: "Enter",
mac: "Enter",
sender: "editor|cli"
},
exec: () => {
setValue(ed.getValue());
// Handle new value;
}
});
ed.on("paste", e => {
e.text = e.text.replace(/[\r\n]+/g, " ");
});
setEditor(ed);
ed.getSession().on("change", e => {
if (e.action == "insert" && ed.session.getValue().includes("\n")) {
setTimeout(() => {
// doing a replaceAll during a change event causes issues in the
// worker, so we'll queue up the change
ed.find(String.fromCharCode(10));
ed.replaceAll("");
ed.selection.clearSelection();
}, 0);
}
});
ed.renderer.on("beforeRender", (e, renderer) => {
const rSession = renderer.session;
const text = rSession.getLine(0);
const charCount = rSession.$getStringScreenWidth(text)[0];
const width =
Math.max(charCount, 2) * renderer.characterWidth + // text size
2 * renderer.$padding + // padding
2 + // little extra for the cursor
0; // add border width if needed
renderer.container.style.width = width + "px";
renderer.onResize(false, 0, width, renderer.$size.height);
});
ed.setWrapBehavioursEnabled(false);
ed.session.setUseWrapMode(false);
ed.focus();
}
} else {
if (editor) {
editor.renderer.on("beforeRender", () => {});
editor.destroy();
setEditor(undefined);
}
}
}, [editing]);
return <div ref={editDiv} style={{ width: "1em", height: "1.2em" }} />;