使用 Draft.js 从字符串创建状态时设置光标位置

Set cursor position when creating a state from a string with Draft.js

Draft.js 上创建包含内容和一些装饰器的 EditorState 后如何设置光标位置。它总是从位置 0 开始。

事情是这样的:

这就是我想要的:

这是我创建状态的方式。

  constructor(props) {
    super(props)
    this.state = { editorState: this.getEditorState() }
  }

  getEditorState() {
    const { reply: { channel, userAccount } } = this.props
    const content = this.getEditorContent({ channel, userAccount })
    const decorators = this.getEditorDecorators(channel)
    return EditorState.createWithContent(content, decorators)
  }

  getEditorContent({ channel, userAccount }) {
    const content = channel && channel.prefill(userAccount)
    return ContentState.createFromText(content || '')
  }

  getEditorDecorators({ decorators }) {
    return getDecorators(decorators || [])
  }

看完issue 224 from Draft.js repository, I've found a static method called moveSelectionToEnd。我需要做的就是用这种方法包装全新的状态,这样。

  getEditorState() {
    const { reply: { channel, userAccount } } = this.props
    const content = this.getEditorContent({ channel, userAccount })
    const decorators = this.getEditorDecorators(channel)
    const state = EditorState.createWithContent(content, decorators)
    return EditorState.moveSelectionToEnd(state)
  }