2

如何将 Draft-js 中的数据保存到 Meteor?

我试着...

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

这是Draft.js。这是Meteor 入门套件。还有这篇文章似乎很相关。

但我无法将这些信息应用到项目中。

考虑到我的 ~/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”&gt;
        <h1>Draft.js Editor</h1>
        <button onClick={this._onBoldClick.bind(this)}>Bold</button>
        <div className=”editor”&gt;
          <Editor
            editorState={this.state.editorState}
            onChange={this.onChange}
          />
        </div>
      </div>
    );
  }
}
4

1 回答 1

3

您可以转换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 */);
  }
  // ...
}

然后转换rawContenteditorState

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

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

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

const editorState = EditorState.createWithContent(blocks);
于 2017-02-06T05:09:17.377 回答