4

使用 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);

任何在正确方向上的有用评论都会很有用

4

3 回答 3

8

当您调用EditorState.createWithContent(c)Draft 时,将为您返回一个新EditorState的,但它不知道您当前的SelectionState. 相反,它只会在 new 的第一个块中创建一个新的空选择ContentState

为了克服这个问题,您必须使用当前状态设置SelectionState自己,例如:SelectionState

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

this.setState({
  editorState: stateWithContentAndSelection
})
于 2017-05-10T15:09:46.820 回答
0

您需要做的就是传递您给定的EditorState内置静态EditorState.moveSelectionToEnd()方法:

const editorState = EditorState.createEmpty();
const editorStateWithFocusOnTheEnd = EditorState.moveSelectionToEnd(editorState)
于 2021-11-02T23:24:23.260 回答
0

有一个属性可以将焦点移到末尾:

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

这对我有用。

于 2020-09-01T10:13:44.577 回答