1.富文本编辑器
一. 安装
2 react‐draft‐wysiwyg
模块引入网址
3draft‐js
4 draftjs‐to‐html
5 html‐to‐draftjs
二 使用demo
https://jpuri.github.io/react‐draft‐wysiwyg/#/demo
三.使用编辑器
import React, { Component } from 'react'
// 1.引入模块
import { Editor } from 'react-draft-wysiwyg';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
//2引入draftjs-to-html 把内容转成html格式
import draftToHtml from 'draftjs-to-html'
// 3.引入html-to-draft 把内容转成draft格式
import htmlToDraft from 'html-to-draftjs'
import { EditorState, ContentState } from 'draft-js';
export default class RichEditor extends Component {
state={
editorState:"",//1.同步编辑器状态
contentState:""//3.编辑的内容状态
}
componentDidMount(){
// 3.引入html-to-draft时需把以下代码写上 在引入react‐draft‐wysiwyg模块时,在此docs(https://jpuri.github.io/react-draft-wysiwyg/#/docs?_k=jjqinp)中可查找到
if(!this.props.content) {//当共用同一组件时,应判断传来的参数是否为空
return;
}
const html = this.props.content;
const contentBlock = htmlToDraft(html);
if (contentBlock) {
const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
const editorState = EditorState.createWithContent(contentState);
this.setState({
editorState
})
}
}
render() {
return (
<div>
{/*1. 使用编辑器 */}
<Editor
editorState={this.state.editorState}
toolbarClassName="toolbarClassName"//工具栏样式
wrapperClassName="wrapperClassName"//内容样式
editorClassName="editorClassName"//整个编辑器样式
onEditorStateChange={this.onEditorStateChange}
onContentStateChange={this.onContentStateChange}
onBlur={()=>{ // 编写内容后,失去焦点再调用getContent函数把内容传给父组件
this.props.getContent(draftToHtml(this.state.contentState))
}}
/>
</div>
)
}
//2. 监听内容的输入,拿得到输入的具体内容 需要引入draftjs-to-html 把内容转成html格式
onContentStateChange=(contentState)=>{
//3. 每输入一下会调用一次,应改为在失去焦点是打印,或者在点击下一步的时候调用getContent这个函数
// this.props.getContent(draftToHtml(contentState))
this.setState({
contentState
})
}
/*1.编辑器有任何改变都会把内容当做形参传给editorState*/
onEditorStateChange=(editorState)=>{
this.setState({
editorState
})
}
}
2. 如果表单初始化的数据是异步获取的,可以setFieldsValue动态设置默认值
this.refs.form.setFieldsValue({
title:res.data.title,
category:res.data.category
});
3.preview预览界面
<div dangerouslySetInnerHTML={{__html:this.state.content}}></div>