React中实现富文本编辑器

React中实现富文本编辑器

前言
在React中实现富文本编辑器,我们可以使用现有的第三方库,如react-quilldraft-js等。这里以react-quill为例进行介绍。

首先需要安装react-quill库:

npm install react-quill --save

然后在需要使用富文本编辑器的组件中引入并使用:

import React, {
    
    useState} from "react";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";

function RichTextEditor() {
    
    
  const [editorContent, setEditorContent] = useState("");

  const handleEditorChange = (content, delta, source, editor) => {
    
    
    setEditorContent(content);
  };

  return (
    <div className="rich-text-editor">
      <ReactQuill
        value={
    
    editorContent}
        onChange={
    
    handleEditorChange}
        modules={
    
    {
    
    
          toolbar: [
            [{
    
     header: [1, 2, false] }],
            ["bold", "italic", "underline", "strike", "blockquote"],
            [
              {
    
     list: "ordered" },
              {
    
     list: "bullet" },
              {
    
     indent: "-1" },
              {
    
     indent: "+1" },
            ],
            ["link", "image"],
            ["clean"],
          ],
        }}
        placeholder="请输入内容"
      />
    </div>
  );
}

export default RichTextEditor;

上述代码中,使用useState来保存编辑器的内容,handleEditorChange函数用于处理编辑器内容变化的事件。

ReactQuill组件作为富文本编辑器的主体,使用了valueonChange属性来设置和获取编辑器的内容。

modules属性是用来配置富文本编辑器的,这里使用了内置的工具栏。

placeholder属性用于在编辑器内容为空时显示占位符。

组件会自动将编辑器的内容转换为HTML格式,可以通过editorContent属性获取HTML格式的内容。

此外,需要在组件中加载quill.snow.css文件,这是编辑器所依赖的样式文件。

猜你喜欢

转载自blog.csdn.net/NIKKT/article/details/129953914