美文网首页
React集成wangEditor

React集成wangEditor

作者: 爱吃豆包 | 来源:发表于2021-04-17 12:22 被阅读0次

富文本在后台管理系统使用的比较多!

在react里面,我这里选择 wangeditor 富文本

需要进行二次封装成组件!因为我这里是使用 Antd 组件库,并且还要让 wangeditor 可以放在 Form 表单使用,进行自动托管!

安装 wangeditor 富文本

npm i wangeditor --save

开始使用

import E from 'wangeditor'

/**
* 这里用函数式组件
*/

let editor = null
function App(props) {

 const { value, onChange } = props;

 useEffect(() => {
   // 注:class写法需要在componentDidMount 创建编辑器
   editor = new E("#div1")

   editor.config.onchange = (newHtml) => {
       onChange(newHtml);
  }

   // 需要展示的菜单
   editor.config.menus = [
       'head',
       'bold',
       'fontSize',
       'fontName',
       'italic',
       'underline',
       'strikeThrough',
       'indent',
       'lineHeight',
       'foreColor',
       'backColor',
       'link',
       'list',
       'todo',
       'justify',
       'quote',
       'table',
       'splitLine',
       'undo',
       'redo',
  ]

   /**一定要创建 */
   editor.create()



   return () => {
     // 组件销毁时销毁编辑器 注:class写法需要在componentWillUnmount中调用
     editor.destroy()
  }

 // 这里一定要加上下面的这个注释  
 // eslint-disable-next-line react-hooks/exhaustive-deps
}, [])

 useEffect(() => {
     if (editor) {
       editor.txt.html(value);
    }
}, [value])

 return (
   <div>
     <div id="div1"></div>
   </div>
);
}

export default App;</pre>

在 Antd 组件库里面的Form组件中使用

// 引入我们二次封装的 wangEditor 富文本组件库
import Editor from '../../../components/editor';

/// 省略一大份代码


<Form>
{/* 省略一大大部分其他代码.... */}

<Form.Item label="内容">
    {getFieldDecorator('content')(<Editor/>)}
 </Form.Item>
</Form>

这个是时候我只需要拖管给 Form 表单组件即可,在查询详情的时候,只要对应相应的字段,那么 Form 会自动给富文本赋值!

image.png

相关文章

网友评论

      本文标题:React集成wangEditor

      本文链接:https://www.haomeiwen.com/subject/jimulltx.html