使用适当的标记将Draft.js Html渲染为div标签?

问题描述 投票:0回答:1

我正在寻找使用draft.js,我想知道我怎么能有一个编辑器,而有人输入结果将显示为html,但实际标记(即如果我做粗体,输出显示粗体)。

我无法让这个工作。我试过dangerouslySetInnerHTML,但似乎没有用。

  <div dangerouslySetInnerHTML={{ __html: this.state.editorContentHtml }}></div>


import React from "react";
import { Editor, EditorState } from "draft-js";
import { stateToHTML } from "draft-js-export-html";

class ExampleEditor1 extends React.Component {
  constructor(props) {
    super(props);
    this.state = { editorState: EditorState.createEmpty() };
    this.onChange = editorState => {
      this.setState({
        editorState,
        editorContentHtml: stateToHTML(editorState.getCurrentContent())
      });
    };
  }

  render() {
    return (
      <div>
        <div className="editor-container" style={{ border: "1px solid #000" }}>
          <Editor
            editorState={this.state.editorState}
            onChange={this.onChange}
          />
        </div>
        <h4>Editor content as HTML</h4>
        <div>{this.state.editorContentHtml}</div>

      </div>
    );
  }
}

export default ExampleEditor1;
javascript html reactjs draftjs
1个回答
0
投票

我还没有使用过draft-js-export-html包,而且我很懒。所以我没有指出你的代码不起作用的原因。

但是下面的代码应该完成任务:

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

const styles = {
  editor: {
    border: "1px solid gray",
    display: "block",
    minHeight: "15em"
  }
};

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      editorState: EditorState.createEmpty(),
      preview: null
    };

    this.onChange = editorState => this.setState({
      editorState,
      preview: editorState.getCurrentContent().getPlainText()
    });

    this.setEditor = ref => {
      this.editor = ref;
    };
    this.focusEditor = () => {
      if (this.editor) {
        this.editor.focus();
      }
    };
  }

  render() {
    return (
      <React.Fragment>
        <div style={styles.editor} onClick={this.focusEditor}>
          <Editor
            ref={this.setEditor}
            editorState={this.state.editorState}
            onChange={this.onChange}
          />
        </div>
        <div
          style={{ minHeight: "200px" }}
          dangerouslySetInnerHTML={{ __html: this.state.preview }}
        />
      </React.Fragment>
    );
  }
}

export default App;
© www.soinside.com 2019 - 2024. All rights reserved.