【问题标题】:Know where the cursor is in the text using AceEditor in ReactJS在 ReactJS 中使用 AceEditor 知道光标在文本中的位置
【发布时间】: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 =&gt; { this.ace = c; }}
  • 谢谢,这已被接受,但我应该如何在 console.log 中调用它?
  • 点赞this.ace.focus()
  • 返回一个未定义的。我不知道是什么原因。
  • 组件应该在设置this.ace之前挂载。

标签: javascript reactjs ace-editor


【解决方案1】:

ref 属性指的是 DOM 节点。并且可以通过以下代码访问:

ref={c => { this.ace = c; }}

为了获取光标的位置,AceEditor 有一个 onCursorChange 属性可供您使用。

onCursorChange(selection) {
  const cursorPosition = selection.getCursor();
}

【讨论】:

  • 你成就了我的一天。这正是我所需要的。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2016-04-30
  • 1970-01-01
  • 2015-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-14
相关资源
最近更新 更多