【问题标题】:How to save draft-js editorState data to Meteor?如何将 Draft-js editorState 数据保存到 Meteor?
【发布时间】:2017-06-22 06:53:30
【问题描述】:

如何将 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>
    );
  }
}

【问题讨论】:

标签: javascript mongodb reactjs meteor draftjs


【解决方案1】:

您可以将 editorState 转换为原始 JS 以便将其存储在数据库中:

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

【讨论】:

  • 非常感谢@Khang
猜你喜欢
  • 1970-01-01
  • 2022-01-01
  • 2019-02-08
  • 1970-01-01
  • 2018-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-26
相关资源
最近更新 更多