【发布时间】:2018-11-19 16:23:14
【问题描述】:
我正在利用 Draft-js 和 react-draft-wysiwyg 库来创建一个所见即所得的编辑器。我希望在工具栏中添加一些自定义选项以呈现最终的 HTML,例如内联 line-height。但是,我无法让 Modifier's applyInlineStyle() 函数正常工作。
编辑:
import React, { Component } from "react";
import { ContentState, convertFromHTML, convertFromRaw, convertToRaw, EditorState, Modifier } from "draft-js";
import { Editor } from "react-draft-wysiwyg";
import draftToHtml from "draftjs-to-html";
import "../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
const toolbarOptions = {
options: ["inline"],
inline: {
options: ["bold", "italic", "underline"],
bold: { className: "rich-text-icon" },
italic: { className: "rich-text-icon" },
underline: { className: "rich-text-icon" }
},
};
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
editorState: EditorState.createEmpty(),
finalHTML: ""
};
}
onEditorStateChange = editorState => {
const raw = convertToRaw(editorState.getCurrentContent());
const markup = draftToHtml(raw);
this.setState({
editorState,
finalHTML: markup
});
console.log(markup);
};
render() {
return (
<div>
<div className="App">
<Editor
editorState={this.state.editorState}
onEditorStateChange={this.onEditorStateChange}
toolbar={toolbarOptions}
toolbarCustomButtons={[<ApplyLineHeight />]}
stripPastedStyles={true}
/>
</div>
</div>
);
}
}
自定义行高选项:
class ApplyLineHeight extends Component {
applyLineHeight = () => {
const { editorState, onChange } = this.props;
const contentState = Modifier.applyInlineStyle(editorState.getCurrentContent(), editorState.getSelection(), "line-height: 20px;");
onChange(EditorState.push(editorState, contentState, "change-inline-style"));
};
render() {
return <div onClick={this.applyLineHeight}>Change line height</div>;
}
}
当我按照docs 中的示例(在“向工具栏添加新选项”下)进行操作时,它可以与Modifier.replaceText() 函数一起使用(替换文本),但在尝试返回行高时它不起作用.我返回了相同的 <p></p> 标签,没有应用内联样式。什么可能导致此函数无法呈现?
【问题讨论】:
-
手动应用内联样式后,您似乎没有返回“已处理”。如果您只是在
onChange(EditorState.push(editorState, contentState, "change-inline-style"));之后返回“已处理”,它可能会解决问题。目前,Draft 也在处理相同的操作,这可能会搞砸。 -
你是怎么解决这个问题的?
-
这方面有什么进展吗?我有同样的问题
标签: javascript reactjs