react中使用simditor富文本编辑器
react 中 使用 沒有啟用圖片上傳功能的simditor 富文本編輯器
- 環(huán)境介紹
- 功能需求
- 步驟實(shí)現(xiàn)
- npm安裝simditor依賴
- jsx頁(yè)面引入
- componentDidMount 獲取DOM 綁定編輯器
- render中的代碼
- 問題解決
環(huán)境介紹
nodejs + npm + react + ant
功能需求
添加富文本編輯器功能:只需要一些常用功能,不需要文件上傳,圖片上傳。界面盡量清新簡(jiǎn)潔。因此 富文本編輯器的選擇 simditor
步驟實(shí)現(xiàn)
npm安裝simditor依賴
npm install jquery --save-devnpm install simditor --save-dev注:安裝只保存在開發(fā)環(huán)境下,生產(chǎn)環(huán)境直接生成靜態(tài)文件所以不需要生產(chǎn)環(huán)境
jsx頁(yè)面引入
jsx頁(yè)面引入:必要的包(一個(gè)form表單里的富文本,修改保存)
import React from "react";import {Form, Input } from "antd";const createForm = Form.create;const FormItem = Form.Item;import $ from "jquery" ;import Simditor from "simditor";componentDidMount 獲取DOM 綁定編輯器
在 componentDidMount 中獲取真是DOM 綁定編輯器創(chuàng)建實(shí)例,并設(shè)置值
this.editor.on是編輯器監(jiān)聽內(nèi)容改變事件,用于將該值賦值給下面真是的desc字段
render中的代碼
直接返回render的代碼(前兩天剛看一本react書籍,其中render的建議就是不要有state的改變,所以未優(yōu)化)
render() {const {getFieldDecorator, getFieldError, isFieldValidating} = this.props.form;// 初始化form表單的值this.state.data = this.props.init.data;// 判斷 改編后賦值與改變前是否一致。一致則跳出if(this.editor !==undefined ){let desc = this.editor.getValue();if(this.state.data.Description !== desc){this.editor.setValue(this.state.data.Description);}}return (<div><Form layout="horizontal">//simditor 富文本編輯器的textarea <textarea className="form-control" ref="simditor" placeholder="這里輸入內(nèi)容" rows="10" ></textarea>//實(shí)際存儲(chǔ)并保存的富文本編輯器內(nèi)容的隱藏字段{getFieldDecorator('Description', {initialValue: this.state.data.Description})(<Input type="hidden" />)}//隱藏主鍵<Input type="hidden" {... getFieldDecorator('Id', {initialValue: this.state.data.Id})} /></Form></div>);}問題解決
-
以上代碼遇到問題 :開始沒有做上一次賦值和本次賦值一致判斷,所以導(dǎo)致死循環(huán)。富文本一旦該改變,則 this.editor.on(“valuechanged”, (e, src))方法執(zhí)行,對(duì)state賦值,然后 render 里又改變。解決加一層判斷
-
第二個(gè)大坑:我的項(xiàng)目是使用less編譯生成css,而富文本編輯器的是 sass和css的。所以項(xiàng)目無法加載編輯器的樣式,解決辦法。新建一個(gè)文件夾,把simditor.css 復(fù)制并改名為simditor.less.然后在項(xiàng)目的統(tǒng)一less入口導(dǎo)入這個(gè)文件即可。
總結(jié)
以上是生活随笔為你收集整理的react中使用simditor富文本编辑器的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 20210101英语单词学习(仅供自己记
- 下一篇: vsnprintf函数用法