這是一個系統的完整的教程,每一節文章的內容都很重要。這個教程學完后自己可以開發出一個相當完美的富文本編輯器了。下面就開始我們今天的內容:
安裝
是的,我們的開發是基于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-react'function 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-react'const 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-react'const 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;
這樣一個基本的富文本編輯器就完成了。但這只是萬里長征的第一步。