好看响应式网站模板下载,可以访问的国外网站,做电子商务网站建设工资多少钱,免费关键词优化工具这是一个系统的完整的教程#xff0c;每一节文章的内容都很重要。这个教程学完后自己可以开发出一个相当完美的富文本编辑器了。下面就开始我们今天的内容#xff1a;
安装
是的#xff0c;我们的开发是基于Slate的开发基础#xff0c;所以要安装它#xff1a;
yarn ad… 这是一个系统的完整的教程每一节文章的内容都很重要。这个教程学完后自己可以开发出一个相当完美的富文本编辑器了。下面就开始我们今天的内容
安装
是的我们的开发是基于Slate的开发基础所以要安装它
yarn add slate slate-react这样就可以了。 使用的时候像下面这样引入相关的依赖
import React, { useState } from react
import { createEditor } from slate
import { Slate, Editable, withReact } from slate-react当然slate的功能很多按需引用即可。
开始
我们先来创建一个组件用以我们的开始
SDocer.jsx
...
function SDocer(){_return null;
}这个组件就做为我们学习开发富文本编辑器的开始。接下来我们要创建一个Editor对象我们需要它的状态与渲染之间保持稳定所有我们用useState来作为桥接工具。
import { useState } from react
import { createEditor } from slate
import { withReact } from slate-reactfunction SDocer(){const [editor] useState(() withReact(createEditor()))return null;
}export default SDocer现在什么都没有我们没有渲染任何东西。这个时候我们需要一个上下文对象把相关的插件功能附上去。这个上下文就是Slate, 先定义一个初始值
import { useState } from react
import { createEditor } from slate
import { Slate, withReact } from slate-reactconst initialValue [{type: paragraph,children: [{ text: 这是一行段落文字内容很少但很重要 }],},
];function SDocer(){const [editor] useState(() withReact(createEditor()))return Slate editor{editor} initialValue{initialValue} /
}export default SDocer我们可以把这个Slate/组件当作一个环境对象所有富文本的相关功能都必须在这个对象中执行才能起作用。也就是所谓的上下文, 虽然呈现的内容可以很复杂但它的内部数据格式却是很简单的就是一个 Json数组格式这就小巧很多了方便传输与保存。
到目前为止虽然我们有了上下文但没有显示 /编辑它的主体所以还是什么也没有。添加一个Editable/主体
import { useState } from react
import { createEditor } from slate
import { Slate, withReact, Editable } from slate-reactconst initialValue [{type: paragraph,children: [{ text: 这是一行段落文字内容很少但很重要 }],},
];function SDocer() {const [editor] useState(() withReact(createEditor()))return (Slate editor{editor} initialValue{initialValue}Editable //Slate)
}export default SDocer注意每一步的引入内容都有变化。为了养成良好的开发习惯我们一定要从一开始就要把数据规划好。添加一个configure把相关的初始化信息及配置信息放在里面。
_configure.jsx
export const initialValue [{type: paragraph,children: [{ text: 这是一行段落文字内容很少但很重要 }],},
];修改 SDocer.jsx如下引入 initialValue
SDocer.jsx
import { useState } from react;
import { createEditor } from slate;
import { Slate, withReact, Editable } from slate-react;import { initialValue } from ./_configure;function SDocer() {const [editor] useState(() withReact(createEditor()));return (Slate editor{editor} initialValue{initialValue}Editable //Slate)
}export default SDocer;这样一个基本的富文本编辑器就完成了。但这只是万里长征的第一步。