我无法从draft-js获取HTML输出?

34

我一直在使用Facebook的draft-js,但实际上我不知道如何获取编辑器的html输出。在下面的示例中,console.log输出了一些_map属性,但它们似乎并没有包含我的实际内容?

class ContentContainer extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          value: '',
          editorState: EditorState.createEmpty()
        };
        this.onChange = (editorState) => this.setState({editorState});
        this.createContent = this.createContent.bind(this);
      }

      createContent() {
        console.log(this.state.editorState.getCurrentContent());
      }

      render() {
        const {editorState} = this.state;
        const { content } = this.props;
        return (
          <Template>
            <br /><br /><br />
            <ContentList content={content} />
            <div className="content__editor">
              <Editor editorState={editorState} onChange={this.onChange} ref="content"/>
            </div>
            <FormButton text="Create" onClick={this.createContent.bind(this)} />
          </Template>
        );
      }
    }
6个回答

50

我用过一个方便的库,draft-js-export-html。导入这个库后,只需调用 stateToHTML 函数即可看到 HTML:

console.log(stateToHTML(this.state.editorState.getCurrentContent()));

我对 React 还比较新,希望这可以对你有所帮助。在查看 contentState 的内部结构时,发现有很多内容需要解析,因此使用该库处理实体更加方便。

作者 sstur 在回答了一个与此有关的问题,我就是从那里了解到他的库的。


3
请考虑一下这个,它是在draftjs官方例子中使用的:https://github.com/hubspot/draft-convert - Yousef Salimpour
必须通过 import { stateToHTML } from "draft-js-export-html"; 导入它,然后将其用作 onChange={(e: EditorState) => { onTranslationChange && onTranslationChange( stateToHTML(e.getCurrentContent()), localization.language ); }} - danivicario
22
我不明白,为什么这样一个花哨的编辑器让获取HTML变得如此困难?获取HTML不是编辑器最重要的需求吗? - Jason Ching
这个插件不会向HTML添加内联样式,有没有一种方法可以获取内联样式和HTML? - CoderBeginner

14

Ewan。我也在使用Draft.js,遇到了同样的问题。事实上,Victor提供了一个很好的解决方案。

这里有两个库,我找到的那个被Victor提到的在GitHub上有更多的星星。

https://github.com/sstur/draft-js-export-html

https://github.com/rkpasia/draft-js-exporter

我只想补充一点,即有一种方法可以在不使用外部库的情况下打印出内容(以JSON格式)。它在数据转换会议记录中有记录。

以下是我如何使用“convertToRaw”函数打印出用户输入的方法

console.log(convertToRaw(yourEditorContentState.getCurrentContent())); 

请确保您通过以下方式从Draft.js导入convertToRaw函数:

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

这是一篇由 rajaraodv 写的博客,名为 How Draft.js 表示富文本数据。它详细解释了数据转换。


2
import {convertFromRaw, convertToRaw} from 'draft-js'; 从 'draft-js' 导入 {convertFromRaw, convertToRaw}。 - Ahsan S. Sher

12

有一个只生成HTML的readonly属性:

<Editor editorState={editorState} readOnly/>

1
添加完这个之后,我该如何获取JSON数据呢?能否再详细解释一下?目前我正在尝试使用this.editorRef.current.editor.innerHTML进行提取,但是即使没有设置为只读模式,它也可以正常工作。但是我有一种感觉这样做可能不正确。 - Kaushik
请注意,如果您已经在此项目中使用draft-js,则这很有效。但是,如果您从数据库导入draft-js数据,并且仅为了转换为HTML而导入draft-js,则非常昂贵(例如,比draft-js-export-html的未打包大小高12倍)。回答@Kaushik的问题,您不需要尝试解析JSON;您需要将有效的draft-js“EditorState”对象传递给“editorState”字段。如果您不确定如何获取该状态,请查看draft-js文档-此链接可能有所帮助:https://draftjs.org/docs/api-reference-data-conversion/ - Andrew

3

如果不想在您的代码中添加另一个库,@farincz的方法可以很好地发挥作用。

<Editor editorState={this.state.editorState} readOnly/>

编辑器状态可以直接存储在您的存储层中,当您将其渲染到DOM中时,它很容易获得并有助于编辑。
通过单击文本,您可以使其可编辑,或将该单击与编辑按钮绑定。您无法直接将单击绑定到“Editor”组件,但可以将其放在包含“Editor”的包装器上。
<div className="editor" onClick={this.editContent.bind(this)}>
  <Editor
    editorState={this.state.editorState}
    onChange={this.onChange}
    handleKeyCommand={this.handleKeyCommand}
    readOnly={this.state.edit}
  />
</div>

只需将“edit”添加到状态中并将其设置为true,确保readOnly为true(如果名称不清楚,可以将状态的名称更改为更明显的“edit”)。

this.state = {
 editorState: EditorState.createEmpty(), 
 edit: true
};

在点击时,最后将 'edit' 的值更改为 false。
editContent() {
  this.setState({
    edit: false
  })
}

2

除了上面分享的库外,这里还有一个不错的库:draftjs-to-html

它可以将原始编辑器状态(JSON对象)转换为普通的HTML。

import draftToHtml from 'draftjs-to-html';
import {convertToRaw} from "draft-js";

const rawContentState = convertToRaw(editorState.getCurrentContent());
const markup = draftToHtml(rawContentState);

1
最适合将内容转换为HTML并从HTML转换的包是 draft-convert
然而,您应该注意使用 高级用法 来能够转换链接并自定义转换过程:
const htmlResult = convertToHTML({
  entityToHTML: (entity, originalText) => {
    if (entity.type === 'LINK') {
      return <a href={entity.data.url}>{originalText}</a>;
    }
    return originalText;
  }
})(editorState.getCurrentContent());


const contentState = convertFromHTML({
    htmlToEntity: (nodeName, node, createEntity): any | void => {
        if (nodeName === 'a') {
            return createEntity(
                'LINK',
                'MUTABLE',
                {url: node.href}
            )
        }
    }
})(htmlInput);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接