Как остановить курсор DraftJS, переходящий в начало текста?

Код, связанный с использованием приложения DraftJS и приложения Meteor Js. Задача - Сделать предварительный просмотр, где текст из DraftJS будет сохранен в БД, а из БД - в другом компоненте.

Но проблема в том, что как только данные поступают из БД, и я пытаюсь отредактировать курсор DraftJS, перемещенный в начало.

Код

import {Editor, EditorState, ContentState} from 'draft-js';
import React, { Component } from 'react';
import { TestDB } from '../api/yaml-component.js';
import { createContainer } from 'meteor/react-meteor-data';
import PropTypes from 'prop-types';

class EditorComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
        editorState : EditorState.createEmpty(),
    };
  }

  componentWillReceiveProps(nextProps) {
    console.log('Receiving Props');
    if (!nextProps) return;
    console.log(nextProps);
    let j = nextProps.testDB[0];
    let c = ContentState.createFromText(j.text);
    this.setState({
      editorState: EditorState.createWithContent(c),
    })
  }

  insertToDB(finalComponentStructure) {
    if (!finalComponentStructure) return;
    finalComponentStructure.author = 'Sandeep3005';
    Meteor.call('testDB.insert', finalComponentStructure);
  }


  _handleChange(editorState) {
    console.log('Inside handle change');
    let contentState = editorState.getCurrentContent();
    this.insertToDB({text: contentState.getPlainText()});
    this.setState({editorState});
  }

  render() {
    return (
      <div>
        <Editor
          placeholder="Insert YAML Here"
          editorState={this.state.editorState}
          onChange={this._handleChange.bind(this)}
        />
      </div>
    );
  }
}


    EditorComponent.propTypes = {
     staff: PropTypes.array.isRequired,
    };

    export default createContainer(() => {
      return {
        staff: Staff.find({}).fetch(),
      };
    }, EditorComponent);

Любой полезный комментарий в правильном направлении будет полезен

3 ответа

Решение

Когда вы звоните EditorState.createWithContent(c) Черновик вернет новый EditorState для вас, но он не имеет никакого представления о вашем нынешнем SelectionState, Вместо этого он просто создаст новый пустой выбор в первом блоке вашего нового ContentState,

Чтобы преодолеть это, вам придется установить SelectionState себя, используя SelectionState от вашего текущего состояния, например:

const stateWithContent = EditorState.createWithContent(c)
const currentSelection = this.state.editorState.getSelection()
const stateWithContentAndSelection = EditorState.forceSelection(stateWithContent, currentSelection)

this.setState({
  editorState: stateWithContentAndSelection
})

Есть свойство переместить фокус в конец:

const newState = EditorState.createEmpty()
this.setState({
 editorState:
  EditorState.moveFocusToEnd(newState)
 })

У меня это работает.

Все, что вам нужно сделать, это передать свое EditorState внутри встроенный статический EditorState.moveSelectionToEnd() метод:

      const editorState = EditorState.createEmpty();
const editorStateWithFocusOnTheEnd = EditorState.moveSelectionToEnd(editorState)
Другие вопросы по тегам