0

我无法在 React-draft-wysiwyg 中加载默认值样式。Codesandbox 链接:编辑器

我试过什么?我正在使用 react-draft-wysiwyg 库进行编辑器和 draft-js 进行初始化和转换,并且我已经通过样式传递了默认值。如果我删除样式标签,它工作正常。但是添加样式后它不起作用。如何修复默认值的样式问题

import { Editor } from "react-draft-wysiwyg";
import { EditorState, ContentState, convertFromHTML } from "draft-js";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
export default function App() {
  const defaultValueRender = !true;
  const defaultValue = "**<p style="color:red**">This is a paragraph.</p>";

  const initialState = () => EditorState.createEmpty();

  const [editorState, setEditorState] = useState(initialState);

  useEffect(() => {
    if (defaultValue !== "") {
      setEditorState(
        EditorState.createWithContent(
          ContentState.createFromBlockArray(convertFromHTML(defaultValue))
        )
      );
    }
  }, []);

  const onChange = async (value) => {
    await setEditorState(value);
  };
  return (
    <div className="App">
      <Editor
        editorState={editorState}
        toolbarClassName="toolbarClassName"
        wrapperClassName="wrapperClassName"
        editorClassName="editorClassName"
        onEditorStateChange={(value) => onChange(value)}
        stripPastedStyles
        ariaLabel="draftEditor"
      />
    </div>
  );
}

4

1 回答 1

0

您可以使用html-to-draftjs内联样式转换 html 字符串。

import React, { useState } from 'react';
import PropTypes from 'prop-types';
// DRAFT
import { EditorState, ContentState, convertToRaw } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
// PURIFY
import DOMPurify from 'dompurify';
// INITIAL STATE
// EditorState.createWithContent(ContentState.createFromBlockArray(convertFromHTML(defaultValue)))
const getInitialState = (defaultValue) => {
  if (defaultValue) {
    const blocksFromHtml = htmlToDraft(defaultValue);
    const { contentBlocks, entityMap } = blocksFromHtml;
    const contentState = ContentState.createFromBlockArray(contentBlocks, entityMap);
    return EditorState.createWithContent(contentState);
  } else {
    return EditorState.createEmpty();
  }
};

const DraftEditor = ({ defaultValue, onChange }) => {
  const [editorState, setEditorState] = useState(getInitialState(defaultValue));
  const onEditorChange = (val) => {
    setEditorState(val);
    const rawContentState = convertToRaw(val.getCurrentContent());
    const htmlOutput = draftToHtml(rawContentState);
    const cleanHtml = DOMPurify.sanitize(htmlOutput);
    onChange && onChange(cleanHtml);
  };

  return (
    <Editor
      editorState={editorState}
      onEditorStateChange={onEditorChange} />
     );
};
DraftEditor.propTypes = {
  defaultValue: PropTypes.string,
  onChange: PropTypes.func.isRequired,
};

export default DraftEditor;
于 2022-02-02T23:37:58.170 回答