62

偶然发现了这个很酷的文本编辑器, Facebook 的draft.js。我尝试按照 Github 中的示例进行操作,但我想创建一个包含内容的编辑器,而不是一个空的编辑器。

var EditorState = Draft.EditorState;

var RichEditor = React.createClass({
   getInitialState(){
      return {editorState: EditorState.createWithContent("Hello")}
      //the example use this code to createEmpty editor
     // return ({editorState: EditorState.createEmpty()})
   }
});

当我运行它时,它会引发错误并显示以下消息“Uncaught TypeError: contentState.getBlockMap is not a function”。

4

9 回答 9

86

EditorState.createWithContent的第一个参数是一个ContentState,而不是一个字符串。您需要导入ContentState

var EditorState = Draft.EditorState;
var ContentState = Draft.ContentState;

使用ContentState.createFromText并将结果传递给EditorState.createWithContent

return {
  editorState: EditorState.createWithContent(ContentState.createFromText('Hello'))
};
于 2016-03-09T07:34:59.380 回答
50

我为 DraftJS 创建了一组包来帮助导入和导出内容(HTML/Markdown)。我在我的项目react-rte中使用了这些。您可能正在寻找的是: npm 上的 draft-js-import-html

npm install draft-js-import-html

如何使用它的示例:

var stateFromHTML = require('draft-js-import-html').stateFromHTML;
var EditorState = Draft.EditorState;

var RichEditor = React.createClass({
  getInitialState() {
    let contentState = stateFromHTML('<p>Hello</p>');
    return {
      editorState: EditorState.createWithContent(contentState)
    };
  }
});

我发布的模块是:

于 2016-03-15T09:31:19.137 回答
17

您可以使用convertFromHTML导入htmlcreateWithContent

import { convertFromHTML, ContentState } from 'draft-js'

const html = '<div><p>hello</p></div>'
const blocksFromHTML = convertFromHTML(html)
const content = ContentState.createFromBlockArray(blocksFromHTML)
this.state = { 
  editorState: EditorState.createWithContent(content)
}

如 Draft 的convertFromHtml 示例所示。请注意,该0.9.1版本无法导入图像,而0.10.0可以。

0.10.0 createFromBlockArray更改为:

const content = ContentState.createFromBlockArray(
  blocksFromHTML.contentBlocks,
  blocksFromHTML.entityMap
)
于 2016-12-05T03:12:56.670 回答
17

有一些 API 更改,为清楚起见,这些示例使用最新的 API,即v0.10.0

有很多方法,但基本上你有三个选项,具体取决于你是想对内容资源使用纯文本、样式文本还是 html 标记。

纯文本是显而易见的,但对于样式文本,您需要使用序列化的 javasript 对象或 html 标记。

让我们从纯文本示例开始:

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

class MyEditor extends Component{

  constructor(props) {
    super(props);

    const plainText = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit.';
    const content = ContentState.createFromText(plainText);

    this.state = { editorState: EditorState.createWithContent(content)};

    this.onChange = (editorState) => {
      this.setState({editorState});
    }
  }
  render(){
    return(
      <Editor
        editorState={this.state.editorState}
        onChange={this.onChange}
      />
    )
  }
}

对于导入样式内容,Draft.js 提供了convertFromRawconvertFromHTML实用功能。

convertFromRaw 函数将原始 javascript 对象作为参数。在这里,我们使用 JSON 字符串化的 javascript 对象作为内容源:

class MyEditor extends Component{

  constructor(props) {
    super(props);

    const rawJsText = `{
      "entityMap": {},
      "blocks": [
        {
          "key": "e4brl",
          "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.",
          "type": "unstyled",
          "depth": 0,
          "inlineStyleRanges": [
            {
              "offset": 0,
              "length": 11,
              "style": "BOLD"
            },
            {
              "offset": 28,
              "length": 29,
              "style": "BOLD"
            },
            {
              "offset": 12,
              "length": 15,
              "style": "ITALIC"
            },
            {
              "offset": 28,
              "length": 28,
              "style": "ITALIC"
            }
          ],
          "entityRanges": [],
          "data": {}
        },
        {
          "key": "3bflg",
          "text": "Aenean commodo ligula eget dolor.",
          "type": "unstyled",
          "depth": 0,
          "inlineStyleRanges": [],
          "entityRanges": [],
          "data": {}
        }
      ]
    }`;

    const content  = convertFromRaw(JSON.parse(rawJsText));
    this.state = { editorState: EditorState.createWithContent(content)};

    this.onChange = (editorState) => {
      this.setState({editorState});
    }
  }
  render(){
    return(
      <Editor
        editorState={this.state.editorState}
        onChange={this.onChange}
      />
    )
  }
}

Draft.js 提供了 convertToRaw 函数,以便您可以将编辑器的状态转换为原始 javascript 对象以进行长期存储。

最后,这里是如何使用 html 标记的:

class MyEditor extends Component{

  constructor(props) {
    super(props);

    const html = `<p>Lorem ipsum <b>dolor</b> sit amet, <i>consectetuer adipiscing elit.</i></p>
      <p>Aenean commodo ligula eget dolor. <b><i>Aenean massa.</i></b></p>`;

      const blocksFromHTML = convertFromHTML(html);
      const content = ContentState.createFromBlockArray(
        blocksFromHTML.contentBlocks,
        blocksFromHTML.entityMap
      );

    this.state = { editorState: EditorState.createWithContent(content)};

    this.onChange = (editorState) => {
      this.setState({editorState});
    }
  }
  render(){
    return(
      <Editor
        editorState={this.state.editorState}
        onChange={this.onChange}
      />
    )
  }
}
于 2017-03-02T09:44:54.143 回答
4

简单来说,您可以从初始阶段将原始 HTML 内容设置为编辑器,或 setState随时使用,如下所示。

editorState: EditorState.createWithContent(ContentState.createFromBlockArray(convertFromHTML('<b>Program</b>')))

导入必要的组件。

import { EditorState, ContentState, convertFromHTML } from 'draft-js'
于 2020-09-05T09:52:01.153 回答
4

当您需要使用纯文本启动编辑器时。

用途EditorState.createWithContentContentState.createFromText方法。工作示例 - https://jsfiddle.net/levsha/3m5780jc/

constructor(props) {
  super(props);

  const initialContent = 'Some text';
  const editorState = EditorState.createWithContent(ContentState.createFromText(initialContent));

  this.state = {
    editorState
  };
}

当您需要使用 html 标记字符串中的内容启动编辑器时。

使用convertFromHTMLContentState.createFromBlockArray。工作示例 - https://jsfiddle.net/levsha/8aj4hjwh/

constructor(props) {
  super(props);

  const sampleMarkup = `
        <div>
        <h2>Title</h2>
        <i>some text</i>
      </div>
    `;

  const blocksFromHTML = convertFromHTML(sampleMarkup);
  const state = ContentState.createFromBlockArray(
    blocksFromHTML.contentBlocks,
    blocksFromHTML.entityMap
  );

  this.state = {
    editorState: EditorState.createWithContent(state),
  };
}

当您有一个字符串数组并且想要使用一些默认的 draft.js 块类型启动编辑器时。

ContentBlocks您可以使用构造函数创建 s 数组new ContentBlock(...),并将其传递给ContentState.createFromBlockArray方法。工作示例unordered-list-item- https://jsfiddle.net/levsha/uy04se6r/

constructor(props) {
  super(props);
  const input = ['foo', 'bar', 'baz'];

  const contentBlocksArray = input.map(word => {
    return new ContentBlock({
      key: genKey(),
      type: 'unordered-list-item',
      characterList: new List(Repeat(CharacterMetadata.create(), word.length)),
      text: word
    });
  });

  this.state = {
    editorState: EditorState.createWithContent(ContentState.createFromBlockArray(contentBlocksArray))
  };
}

当您需要使用ContentState原始 JS 结构中的内容启动编辑器时。

如果您之前将内容状态保存到原始 JS 结构中convertToRaw(请阅读此答案了解详细信息)。您可以使用方法启动编辑器convertFromRaw。工作示例 - https://jsfiddle.net/levsha/tutc419a/

constructor(props) {
  super(props);

  this.state = {
    editorState: EditorState.createWithContent(convertFromRaw(JSON.parse(editorStateAsJSON)))
  };
}
于 2017-10-31T08:23:16.097 回答
1

如果要使用 HTML 格式设置,只需添加以下代码即可将初始值设置为 edtitorState

this.state = {
  editorState: EditorState.createWithContent(
    ContentState.createFromBlockArray(
      convertFromHTML('<p>My initial content.</p>')
    )
  ),
}
于 2018-10-26T11:59:04.300 回答
0

我发现这是一种具有丰富功能的干净方式。您可以在将来添加更多插件,将您的内容导出为.md等,而无需过多更改组件的结构。

import Draft from 'draft-js';

import DraftPasteProcessor from 'draft-js/lib/DraftPasteProcessor';
const { EditorState, ContentState } = Draft;
import Editor from 'draft-js-plugins-editor';

import createRichButtonsPlugin from 'draft-js-richbuttons-plugin';
const richButtonsPlugin = createRichButtonsPlugin();

class DescriptionForm extends React.Component {

state = {
  editorState: this._getPlaceholder(),
}

_getPlaceholder() {
  const placeholder = 'Write something here';
  const contentHTML = DraftPasteProcessor.processHTML(placeholder);
  const state = ContentState.createFromBlockArray(contentHTML);
  return Draft.EditorState.createWithContent(state);
}

_onChange(editorState) {
  this.setState({
    editorState,
  });
}

render () {
    let { editorState } = this.state;
    return (
      <div>
          <Editor
            editorState={editorState}
            onChange={this._onChange.bind(this)}
            spellCheck={false}
            plugins={[richButtonsPlugin, videoPlugin]}
          />
      </div>
    );
  }
}
于 2016-10-14T07:35:51.027 回答
0

对于Nextjs

import React, { Component } from 'react';
import { EditorState, convertToRaw, ContentState, convertFromHTML } from 'draft- 
js';
import draftToHtml from 'draftjs-to-html';
import dynamic from 'next/dynamic';
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";

const Editor = dynamic(
() => import('react-draft-wysiwyg').then(mod => mod.Editor),
{ ssr: false }
)

let htmlToDraft = null;
if (typeof window === 'object') {
htmlToDraft = require('html-to-draftjs').default;
}

export default class EditorConvertToHTML extends Component {
constructor(props) {
    super(props);
    this.state = {
        editorState: EditorState.createEmpty(),
        contentState: ""
     }
    }

 componentDidMount() {

    const html = '<p>Hey this <strong>editor</strong> rocks d</p>';
    const contentBlock = htmlToDraft(html);
    console.log(contentBlock)
     if (contentBlock) {
        const contentState = 
        ContentState.createFromBlockArray(contentBlock.contentBlocks);
        const editorState = EditorState.createWithContent(contentState);
        console.log(editorState)
        this.setState(
            {
                editorState: EditorState.createWithContent(
                    ContentState.createFromBlockArray(
                        convertFromHTML(html)
                    )
                )
            }
          )
         }
        } 

     onEditorStateChange = (editorState) => {
     this.setState({
        editorState,
      });
     };

    render() {
    const { editorState } = this.state;
    console.log(this.state.editorState.getCurrentContent())
    return (
        <div>
            <Editor
                editorState={editorState}
                wrapperClassName="demo-wrapper"
                editorClassName="demo-editor"
                onEditorStateChange={this.onEditorStateChange}
            />
            <textarea
                disabled
                value= 
      {draftToHtml(convertToRaw(editorState.getCurrentContent()))}
            />
         </div>
        );
      }
        }
于 2022-01-31T15:14:23.827 回答