如何阻止DraftJS游标跳转到文本开头?

时间:2017-05-09 11:38:51

标签: mongodb reactjs meteor draftjs draft-js-plugins

使用DraftJS和Meteor Js应用程序涉及的代码 任务 - 进行实时预览,将DraftJS中的文本保存到DB,然后从DB中显示另一个组件。

但问题是,一旦数据来自数据库,我就会尝试将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);

任何有用的评论方向都是有用的

2 个答案:

答案 0 :(得分:1)

当您致电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
})

答案 1 :(得分:0)

将焦点移到末尾是有道理的:

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

这对我有用。