最近在一個項目中需要完成一個富文本編輯的功能拷橘,項目的主要依賴情況如下:
"dependencies": {
"antd": "^2.8.2",
"classnames": "^2.2.5",
"jquery": "^3.2.1",
"lodash": "^4.13.1",
"moment": "^2.14.1",
"query-string": "^3.0.1",
"rc-form": "^0.17.2",
"react": "^15.1.0",
"react-addons-transition-group": "^15.1.0",
"react-cookie": "^1.0.5",
"react-dom": "^15.1.0",
"react-redux": "^4.4.5",
"react-router": "^2.4.1",
"react-router-redux": "^4.0.5",
"react-router-scroll": "^0.2.0",
"redux": "^3.5.2",
"redux-actions": "^0.10.0",
"redux-immutablejs": "^0.0.8",
"redux-promise": "^0.5.3",
"redux-thunk": "^2.1.0",
"reselect": "^2.5.1",
"simditor": "^2.3.6",
"simditor-html": "^1.1.1",
"whatwg-fetch": "^1.0.0"
},
下面介紹下集成simditor的過程:
1徒恋、在html頁面加入了js引用
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.6.14/beautify-html.min.js"></script>
2逞姿、js代碼引入
import Simditor from 'simditor';
import $ from 'jquery';
import '../../../../node_modules/simditor/styles/simditor.css';
import '../../../../node_modules/simditor-html/styles/simditor-html.css';
require( '../../../../node_modules/simditor-html/lib/simditor-html.js');
3、初始化代碼
componentDidMount() {
let id = 'content_' + this.props.type;
var textbox = ReactDOM.findDOMNode(this.refs[id]);
this.editor = new Simditor({
textarea: $(textbox),
toolbar: [
'title',
'bold',
'italic',
'underline',
'strikethrough',
'fontScale',
'color',
'ol',
'ul',
'blockquote',
'code',
'table',
'link',
'image',
'indent',
'outdent',
'alignment',
'hr',
'|',
'html'
],
upload: {
url: URLS.image_upload_url, //文件上傳的接口地址
params: null, //鍵值對,指定文件上傳接口的額外參數(shù),上傳的時候隨文件一起提交
fileKey: 'file', //服務器端獲取文件數(shù)據(jù)的參數(shù)名
connectionCount: 3,
leaveConfirm: '正在上傳文件'
},
});
this.editor.on("valuechanged", (e, src) => {
// todo
});
}
4、render方法 泛源,其中handleSubmit是保存的ajax處理
render() {
let title = this.props.title;
let id = 'content_' + this.props.type;
let val = this.props.val;
return (
<div>
<div style={{marignTop: 10, marginBottom: 10}}>
<Button onClick={this.handleSubmit} htmlType="button" type="danger">保存『{title}』內(nèi)容</Button>
</div>
<textarea className="form-control" ref={id} rows="30">{val}</textarea>
</div>
);
}
5、效果如圖
6、webpack調(diào)整
externals: {
'html_beautify':'html_beautify',
'antd':true,
"react": "React",
"react-dom": "ReactDOM"
},
這個增加了 『html_beautify』這個到externals里面只洒,不然編譯不過。具體的一些細節(jié)可以查看下externals的用法劳坑,這里把react毕谴,react-dom都提取出來通過單獨的js文件加載減少js文件包大小。