New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
I want to get the cursor position. #603
Comments
I need to get the position of the cursor in the editor to implement a text insertion function. What should I do? |
在 CodeMirror v6 中,要向光标位置插入字符串,你可以使用
|
import React, {forwardRef, useCallback, useContext, useEffect, useImperativeHandle, useRef, useState} from 'react'; const AutoCodeMirror = forwardRef(({exprVal, setExprVal}, ref) => { const codeMirrorRef = useRef(null); useImperativeHandle(ref, () => { // 将 codeMirrorRef 暴露给父组件
}, [currentNode]); const onChange = useCallback((val, viewUpdate) => { const myCompletions = (context) => { return (
); export default AutoCodeMirror; 这是我的代码,出现报错 update listener: TypeError: StateEffect.appendText is not a function |
如果有错误,清使用下面工具工具之一提供重现的示例
另外我可能给了个错误的示例,我这里有个 编辑器的实现有类似的插入代码 view.dispatch(
view.state.changeByRange((range) => ({
changes: [
{ from: range.from, insert: '**' },
{ from: range.to, insert: '**' },
],
range: EditorSelection.range(range.from + 2, range.to + 2),
})),
); @ilysusu 你可以参考我封装的 react-markdown-editor 组件代码 |
@ilysusu 示例: https://codesandbox.io/embed/https-github-com-uiwjs-react-codemirror-issues-603-wr6ph9?fontsize=14&hidenavigation=1&theme=dark import React, { useRef, useState } from "react";
import CodeMirror from "@uiw/react-codemirror";
import { StateEffect } from "@codemirror/state";
import { javascript } from "@codemirror/lang-javascript";
import { EditorSelection } from "@codemirror/state";
export default function App() {
const codeMirrorRef = useRef(null);
const [val, setVal] = useState("console.log('hello world!');");
const onChange = React.useCallback((value, viewUpdate) => {
console.log("value:", value);
}, []);
// 从光标位置插入文本
const handleInsertVal = () => {
const view = codeMirrorRef.current.view;
view.dispatch(
view.state.changeByRange((range) => ({
changes: [
{ from: range.from, insert: "**" },
{ from: range.to, insert: "**" }
],
range: EditorSelection.range(range.from + 2, range.to + 2)
}))
);
};
const onRefChange = () => {
codeMirrorRef.current.view.dispatch({
changes: { from: 0, to: 12, insert: "InsertText" }
});
};
return (
<div>
<button onClick={handleInsertVal}> insertValue </button>
<button onClick={onRefChange}>Ref Change Value</button>
<CodeMirror
value={val}
ref={codeMirrorRef}
height="200px"
theme="dark"
extensions={[javascript({ jsx: true })]}
onChange={onChange}
/>
</div>
);
} |
In answer to the issue title (for others looking for an answer to "How to get cursor position"
NOTE: Use |
我需要获取光标在编辑器中的位置,做一个文本插入的功能,需要怎么做
The text was updated successfully, but these errors were encountered: