react hook 使用百度富文本編輯器ueditor

打開官網(wǎng)ueditor官網(wǎng)

https://github.com/fex-team/ueditor#ueditor

看下圖下載,并解壓出來(lái)


01.jpg

02.jpg

然后在此文件打開命令窗口

//如果電腦沒有安裝grunt 執(zhí)行以下第一個(gè)命令
npm install grunt -g
//然后給ueditor安裝依賴
npm install
//再執(zhí)行
grunt default

成功的命令窗口


03.jpg

此時(shí)文件目錄如下圖


04.jpg

然后把dist文件下的目錄 utf8-php 復(fù)制到react項(xiàng)目里的public文件夾里,并改名為ueditor


05.jpg

06.jpg

07.jpg

然后在項(xiàng)目的public的index.html引入以下代碼

<script type="text/javascript" src="/ueditor/ueditor.config.js"></script>
<script type="text/javascript" src="/ueditor/ueditor.all.js"></script>

//上面的如果識(shí)別不了中文可以改引入以下代碼
<!-- <script src="/ueditor3/ueditor.config.js"></script>
     <script src="/ueditor3/ueditor.all.js"></script>
     <script src="/ueditor3/lang/zh-cn/zh-cn.js"></script>
     <script src="/ueditor3/ueditor.parse.min.js"></script> -->
08.jpg

然后修改public里的ueditor文件的ueditor.config.js,如下圖


09.jpg

toolbars的配置代碼

// 工具欄上的所有的功能按鈕和下拉框,可以在new編輯器的實(shí)例時(shí)選擇自己需要的重新定義
    toolbars: [[
      'fullscreen', 'source', '|', 'undo', 'redo', '|',
      'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
      'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
      'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
      'directionalityltr', 'directionalityrtl', 'indent', '|',
      'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
      'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
      'simpleupload', 'insertimage', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'map', 'gmap', 'insertframe', 'insertcode', 'webapp', 'pagebreak', 'template', 'background', '|',
      'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|',
      'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
      'print', 'preview', 'searchreplace', 'drafts', 'help'
    ]],

封裝ueditor組件

import React, {useEffect,useImperativeHandle,forwardRef} from 'react'
let editor = null
 
const UEditor = (props,ref) => {
    useEffect(() => {
        setConfig(props.initData,props.config,props.setContent)
        return ()=>{
            editor.destroy();
            // editor.removeListener(); //不要打開,否則返回有問(wèn)題報(bào)錯(cuò)
        }
    },[props.initData,props.config,props.setContent])
    // 初始化編輯器
    const setConfig = (initData,config,setContent) => {
        editor = window.UE &&window.UE.getEditor('editor', {
            // enableAutoSave: false,
            // autoHeightEnabled: false,
            autoFloatEnabled: false,
            initialFrameHeight: (config&&config.initialFrameHeight) || 450,
            initialFrameWidth: (config&&config.initialFrameWidth) || '100%',
            zIndex: 1,

        })
        editor.ready(() => {
            if(initData){
                editor.setContent(initData)  //設(shè)置默認(rèn)值/表單回顯
            }
        })
        editor.addListener("blur",function(){
            setContent(editor.getContent())
        });
    }
    useImperativeHandle(ref,()=>({
        getUEContent: ()=> {
            return editor.getContent() //獲取編輯器內(nèi)容
        }
    }))
    return (
      <script id="editor" type="text/plain" />
    )
}
 
export default forwardRef(UEditor) 

組件的使用


import React,{useState,useRef} from 'react'
import UEditor from '@/UEditor' 
import './PublishArticle.less'
import {Form,Button,Input,message,Select,Radio} from 'antd'
const {Item} = Form
const { Option } = Select;
function PublishArticle() {
    const [form] = Form.useForm();
    const ueRef = useRef(null)
    const tailLayout = {
        wrapperCol: { offset: 10, span: 8 },
    };
    //選擇欄目
    const onGenderChange = value => {
        console.log(value);
    };
    const [radioVal, setRadioVal] = useState(1)
    //編輯器的寬度
    const [config] = useState({
        initialFrameWidth: '100%',
        initialFrameHeight: 400
    })
    //編輯器的默認(rèn)值
    const [initData] = useState('')
    //富文本失焦就觸發(fā)setContent函數(shù)設(shè)置表單的content內(nèi)容
    const setContent = (e)=>{
        form.setFieldsValue({
            content: ueRef.current.getUEContent()
        })
    }
     //發(fā)布
    const onFinish = (values) => {
        console.log(values);
        message.error('發(fā)布未成功')
    };
    return (
        <div className="PublishArticle-wrap">
            <div className="title">發(fā)布文章</div>
            <Form preserve={false}  style={{width:'750px'}} autoComplete="off" form={form} onFinish={onFinish}>
                <Item name="unit"  label="選擇欄目:" rules={[{ required: true,message: '選擇欄目必選' }]}>
                    <Select
                    placeholder="請(qǐng)選擇選擇欄目"
                    onChange={onGenderChange}
                    allowClear
                    style={{width:"200px"}}
                    >
                        <Option value="1">健康</Option>
                        <Option value="2">子女</Option>
                    </Select>
                </Item>
                <Item name="type"  label="首頁(yè)推薦:" initialValue={1} rules={[{ required: true,message: '首頁(yè)推薦必填' }]}>
                    <Radio.Group style={{width: '200px'}} onChange={(e)=>setRadioVal(e.target.value)} value={radioVal}>
                        <Radio value={1} checked>關(guān)閉</Radio>
                        <Radio value={2}>開啟</Radio>
                    </Radio.Group>
                </Item>
                <Item name="name"  label="文章標(biāo)題:" rules={[{ required: true,message: '文章標(biāo)題必填' }]}>
                    <Input placeholder="請(qǐng)輸入文章標(biāo)題" allowClear/>
                </Item>
                <Item name="content" label="文章內(nèi)容:" initialValue={initData} rules={[{required: true,message: '文章內(nèi)容必填' }]}>
                    <UEditor id="container" ref={ueRef} config={config} initData={initData} setContent={(e)=>setContent(e)}></UEditor>
                </Item>
                <Item {...tailLayout}>
                    <Button type="primary" htmlType="submit">發(fā)布</Button>
                </Item>
            </Form>
        </div>
    )
}

export default PublishArticle

看看顯示效果


10.jpg
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容