2018年4月23日:
前言:
其實(shí)市面上的富文本編輯器還是不少的,在react項(xiàng)目里我們一般會(huì)用wangEditor,最大的原因是他已經(jīng)集成在npm里面了,用起來比較方便,但是功能方面沒有那么齊全,最近項(xiàng)目上有個(gè)問題,客戶要求富文本編輯器里可以設(shè)置行間距,可以在編輯器里調(diào)整圖片大小,搜了一下,可以設(shè)置行間距的不少,可以調(diào)整圖片大小的可能只有百度的Ueditor了。于是入坑百度Ueditor。
官網(wǎng)地址: http://ueditor.baidu.com/website/
不建議下完整版的代碼,需要自己編譯,很可能花大把的時(shí)間編譯不成功。

本文代碼github地址:https://github.com/AMM9394/ueditorTest.git
1、用create-react-app腳手架創(chuàng)建react項(xiàng)目
將下載好的文件夾放在public文件夾下。這里說一下為什么要用create-react-app,我們下好的源碼是要放在跟index.html同一文件夾下的,打包的時(shí)候該文件夾下的文件不會(huì)被打包,同時(shí)要將Ueditor所在的文件夾復(fù)制到打包后的文件夾中,這個(gè)我還沒有去細(xì)看到底webpack做了什么操作,但是creact-react-app產(chǎn)生的打包文件可以做到上述事情。
2018.6.7更新,如果不是create-react-app創(chuàng)建的項(xiàng)目,在開發(fā)時(shí)和前面說的一樣要把文件放在和index.html同一個(gè)文件夾下,一般都是public,然后修改一下webpack相關(guān)的配置。研究了一下create-react-app里面關(guān)于webpack的配置,首先說一下create-react-app的start,build文件都在react-scripts包里面,需要在node-modules里面找到react-scripts才能找到start.js,build.js等。webpack的配置在build.js里面,他多做的事情就是吧public文件夾復(fù)制了一份,如圖所示。如果需要自己配置的話可以參考一下create-react-app的build.js文件,代碼貼在了文章末尾

2、引入及初始化
將下載好的文件夾放入到public文件下,與index.html同級(jí)。
并在index.html里面加入以下代碼
<!-- 配置文件 -->
<script type="text/javascript" src="ueditor/ueditor.config.js"></script>
<!-- 編輯器源碼文件 -->
<script type="text/javascript" src="ueditor/ueditor.all.js"></script>
此時(shí)window對(duì)象里面會(huì)有UE對(duì)象。
在APP.js里面從初始化編輯器
...
componentDidMount(){
let UE = window.UE;
UE.getEditor('container', {
autoHeightEnabled: true,
autoFloatEnabled: true
});
}
...
render(){
return(div>
...
<textarea id="container"></textarea>
</div>);
}
展示效果如圖

3、封裝組件
新建ueditor.js文件封裝udeitor
import React from 'react';
export default class Ueditor extends React.Component {
constructor(props){
super(props);
this.state={
id:this.props.id?this.props.id:null,
ueditor :null,
}
}
componentDidMount(){
let UE = window.UE;
let {id} = this.state;
if(id){
try {
/*加載之前先執(zhí)行刪除操作,否則如果存在頁面切換,
再切回帶編輯器頁面重新加載時(shí)不刷新無法渲染出編輯器*/
UE.delEditor(id);
}catch (e) {}
let ueditor = UE.getEditor(id, {
autoHeightEnabled: true,
autoFloatEnabled: true
});
this.setState({ueditor });
}
}
render(){
let {id} = this.state;
return (
<div>
<textarea id={id} />
</div>
);
}
}
在需要編輯器的頁面引入組件并使用
import Ueditor from './component/ueditor';
...
render(){
return(div>
...
<Ueditor id={'myeditor'}/>
</div>);
4、各種坑
4.1、全屏問題
全屏的處理函數(shù)在ueditor.all.js里面對(duì)函數(shù)進(jìn)行修改即可實(shí)現(xiàn)全屏
源代碼中的設(shè)置編輯器放大是根據(jù)父節(jié)點(diǎn)來放大的,但是既然是放大當(dāng)然全屏比較high啊。so,改代碼吧。
修改后的代碼如下
_updateFullScreen:function () {
if (this._fullscreen) {
var vpRect = uiUtils.getViewportRect();
//修改為無論什么情況都相對(duì)于瀏覽器窗口全屏
//此處的height是整個(gè)編輯器的高度
this.getDom().style.cssText = 'border:0;position:fixed;left:0;top:0' + 'px;width:' + window.innerWidth + 'px;height:' + window.innerHeight + 'px;z-index:' + (this.getDom().style.zIndex * 1 + 1000);
// uiUtils.setViewportOffset(this.getDom(), { left:0, top:this.editor.options.topOffset || 0 });
//設(shè)置編輯器內(nèi)容的高度
this.editor.setHeight(window.innerHeight - this.getDom('toolbarbox').offsetHeight - this.getDom('bottombar').offsetHeight - (this.editor.options.topOffset || 0),true);
//不手動(dòng)調(diào)一下,會(huì)導(dǎo)致全屏失效
if(browser.gecko){
try{
window.onresize();
}catch(e){
}
}
}
},
主要修改的地方如下圖:

圖中修改的position:fixed,如果編輯器父元素設(shè)置了transform屬性的話編輯器還是只相對(duì)于父節(jié)點(diǎn)放大
4.2、Ueditor圖片保存問題
在使用的過程中發(fā)現(xiàn)了一個(gè)很尷尬的問題,就是無論你在編輯器中給圖片什么格式,保存的時(shí)候他都會(huì)把格式去掉,也就是說我們保存的富文本的html里面所有的img標(biāo)簽都沒有style,真的是調(diào)試了很久才發(fā)現(xiàn)問題在哪里。在編輯器的配置文件ueditor.config.js里面有一個(gè)配置whitList,修改這個(gè)配置項(xiàng)里面img的配置(在整個(gè)文件中搜索img即可找到),如圖所示將style放進(jìn)去,保存時(shí)img標(biāo)簽的style屬性才會(huì)被保存,否則該標(biāo)簽會(huì)被移除,也就是說不管圖片格式怎么設(shè)置均不可能保存成功

//2019年1月15日更新
4.3、Ueditor父組件props改變編輯器內(nèi)容不渲染問題(這段解決的不是很合理,我優(yōu)化后再放出來)
//2018年6月8日更新
4.4、一個(gè)頁面實(shí)例化多個(gè)Ueditor編輯器
這個(gè)問題其實(shí)不算問題,主要是代碼習(xí)慣,之前后臺(tái)的小朋友把ueditor作為了全局變量,導(dǎo)致了實(shí)例化兩個(gè)ueditor時(shí),每次更改只保存了最后一個(gè)編輯器的內(nèi)容,所以,必須要把實(shí)例化的編輯器放在state里面,通過state來更新并使用編輯器。同時(shí)在使用頁面兩個(gè)編輯器的id要區(qū)分開。
creact-react-app中build.js的內(nèi)容
// @remove-on-eject-begin
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// @remove-on-eject-end
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const path = require('path');
const chalk = require('chalk');
const fs = require('fs-extra');
const webpack = require('webpack');
const config = require('../config/webpack.config.prod');
const paths = require('../config/paths');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
const printBuildError = require('react-dev-utils/printBuildError');
const measureFileSizesBeforeBuild =
FileSizeReporter.measureFileSizesBeforeBuild;
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
const useYarn = fs.existsSync(paths.yarnLockFile);
// These sizes are pretty large. We'll warn for bundles exceeding them.
const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// First, read the current file sizes in build directory.
// This lets us display how much they changed later.
measureFileSizesBeforeBuild(paths.appBuild)
.then(previousFileSizes => {
// Remove all content but keep the directory so that
// if you're in it, you don't end up in Trash
fs.emptyDirSync(paths.appBuild);
// Merge with the public folder
copyPublicFolder();
// Start the webpack build
return build(previousFileSizes);
})
.then(
({ stats, previousFileSizes, warnings }) => {
if (warnings.length) {
console.log(chalk.yellow('Compiled with warnings.\n'));
console.log(warnings.join('\n\n'));
console.log(
'\nSearch for the ' +
chalk.underline(chalk.yellow('keywords')) +
' to learn more about each warning.'
);
console.log(
'To ignore, add ' +
chalk.cyan('// eslint-disable-next-line') +
' to the line before.\n'
);
} else {
console.log(chalk.green('Compiled successfully.\n'));
}
console.log('File sizes after gzip:\n');
printFileSizesAfterBuild(
stats,
previousFileSizes,
paths.appBuild,
WARN_AFTER_BUNDLE_GZIP_SIZE,
WARN_AFTER_CHUNK_GZIP_SIZE
);
console.log();
const appPackage = require(paths.appPackageJson);
const publicUrl = paths.publicUrl;
const publicPath = config.output.publicPath;
const buildFolder = path.relative(process.cwd(), paths.appBuild);
printHostingInstructions(
appPackage,
publicUrl,
publicPath,
buildFolder,
useYarn
);
},
err => {
console.log(chalk.red('Failed to compile.\n'));
printBuildError(err);
process.exit(1);
}
);
// Create the production build and print the deployment instructions.
function build(previousFileSizes) {
console.log('Creating an optimized production build...');
let compiler = webpack(config);
return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
if (err) {
return reject(err);
}
const messages = formatWebpackMessages(stats.toJson({}, true));
if (messages.errors.length) {
// Only keep the first error. Others are often indicative
// of the same problem, but confuse the reader with noise.
if (messages.errors.length > 1) {
messages.errors.length = 1;
}
return reject(new Error(messages.errors.join('\n\n')));
}
if (
process.env.CI &&
(typeof process.env.CI !== 'string' ||
process.env.CI.toLowerCase() !== 'false') &&
messages.warnings.length
) {
console.log(
chalk.yellow(
'\nTreating warnings as errors because process.env.CI = true.\n' +
'Most CI servers set it automatically.\n'
)
);
return reject(new Error(messages.warnings.join('\n\n')));
}
return resolve({
stats,
previousFileSizes,
warnings: messages.warnings,
});
});
});
}
function copyPublicFolder() {
fs.copySync(paths.appPublic, paths.appBuild, {
dereference: true,
filter: file => file !== paths.appHtml,
});
}