React 版本的真开箱即用的富文本编辑器
这篇文章推荐的react 版的富文本编辑器名字叫做wysiwyg,第一时间你可能觉得这个名字起的很烂,很难记,但是当你知道它的全称后就很好记了,全称为 What you see is what you get(所见即所得)。这个富文本编辑器是偶然在掘金上看到的,宣传上主打开箱即用,在用过后,确实基本能做到开箱即用,基本下载后,不需要进行什么配置。
Github文档地址
官方Demo地址
import React, { Component } from 'react'
import { EditorState, convertToRaw } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
export default class RichTextEditor extends Component {
state = {
editorState: EditorState.createEmpty(),
}
onEditorStateChange = (editorState) => {
this.setState({
editorState,
});
};
getRichText=()=>{
return draftToHtml(convertToRaw(this.state.editorState.getCurrentContent()))
}
setRichText = (html) => {
const contentBlock = htmlToDraft(html);
if(contentBlock){
const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
const editorState = EditorState.createWithContent(contentState);
this.setState = ({editorState});
}
}
render() {
const { editorState } = this.state;
return (
<div>
<Editor
editorState={editorState}
onEditorStateChange={this.onEditorStateChange}
editorStyle={{border: '1px solid slategrey',paddingLeft:'10px',lineHeight:'10px',minHeight:'200px'}}
/>
{}
</div>
);
}
}
父组件中调用:
richTextEditor = React.createRef();
let richText = this.richTextEditor.current.getRichText();
this.richTextEditor.current.setRichText(detail);
<RichTextEditor ref={this.richTextEditor}/>
|