如何将draft-js editorState数据保存到Meteor?

时间:2017-02-05 05:59:28

标签: javascript mongodb reactjs meteor draftjs

如何将数据从draft-js保存到Meteor?

我试图......

  • 将数据从Draft-js保存到数据库
  • 使用React + Meteor

这是Draft.js。这是Meteor starter kit。还有this article似乎相关。

但我不能将这些信息应用到项目中。

考虑我的〜/ imports / collections / bins.js是

import { Mongo } from 'meteor/mongo';

Meteor.methods({
  'bins.insert': function() {
    return Bins.insert({
      createdAt: new Date(),
      content: '',
      sharedWith: [],
      ownerId: this.userId
    });
  },

  'bins.remove': function(bin) {
    return Bins.remove(bin);
  },

  'bins.update': function(bin, content) {
    return Bins.update(bin._id, { $set: { content } });
  }
});

export const Bins = new Mongo.Collection('bins');

考虑A Beginner’s Guide to Draft JS中的指南

import React from ‘react’;
import {Editor, EditorState, RichUtils} from ‘draft-js’;
export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {editorState: EditorState.createEmpty()};
    this.onChange = (editorState) => this.setState({editorState});
  }
  _onBoldClick() {
    this.onChange(RichUtils.toggleInlineStyle(
      this.state.editorState,
      ‘BOLD’
    ));
  }
  render() {
    return (
      <div id=”content”>
        <h1>Draft.js Editor</h1>
        <button onClick={this._onBoldClick.bind(this)}>Bold</button>
        <div className=”editor”>
          <Editor
            editorState={this.state.editorState}
            onChange={this.onChange}
          />
        </div>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

您可以将editorState转换为原始JS,以便将其存储在DB中:

import {
  convertToRaw,
} from 'draft-js';

export default class App extends React.Component {
  // ...
  saveToDb() {
    const contentState = this.state.editorState.getCurrentContent();

    const rawContent = JSON.stringify(convertToRaw(contentState));

    Meteor.call(/* save rawContent to db */);
  }
  // ...
}

然后将rawContent转换回editorState

import {
  convertFromRaw,
  EditorState,
} from 'draft-js';

const rawContent = /* get this value from db */;

const contentState = convertFromRaw(JSON.parse(rawContent));

const editorState = EditorState.createWithContent(blocks);