【发布时间】:2018-06-22 06:47:22
【问题描述】:
我正在创建一个代码编辑器,现在我想知道光标在 Ace Editor 文本中的位置。
这是代码编辑器组件的代码:
import React, {Component} from 'react';
import AceEditor from 'react-ace';
import 'brace/mode/javascript';
import 'brace/theme/monokai';
import 'brace/ext/language_tools';
class EditorCodeEditor extends Component {
onChange = e => {
// Here I want show for console the position of cursor
Something like this? -> console.log(this.refs.ace.editor.focus);
};
render() {
return (
<div>
<AceEditor
mode="javascript"
theme="monokai"
name="blah2"
onChange={this.onChange}
fontSize={14}
showPrintMargin={true}
showGutter={true}
highlightActiveLine={true}
value="I AM AN EDITOR"
ref='ace'
focus={true}
cursorStart={1}
editorProps={{$blockScrolling: true}}
style={{width: '100%', height: '400px'}}
setOptions={{
enableBasicAutocompletion: false,
enableLiveAutocompletion: true,
enableSnippets: true,
showLineNumbers: true,
tabSize: 2
}} />
</div>
);
}
}
export default EditorCodeEditor;
问题是当我在 AceEditor 标签中使用 ref='ace' 时,它返回 错误:不推荐在 ref 属性中使用字符串文字。 (react/no-string-refs) 和 this.refs 一样进入 onChange 函数。
对此有什么想法吗?感谢您的帮助。
【问题讨论】:
-
试试
ref={c => { this.ace = c; }} -
谢谢,这已被接受,但我应该如何在 console.log 中调用它?
-
点赞
this.ace.focus() -
返回一个未定义的。我不知道是什么原因。
-
组件应该在设置
this.ace之前挂载。
标签: javascript reactjs ace-editor