1、Basic
插件只是一个普通的JavaScript对象,其中包含一些更深层的嵌套对象或函数
const customPlugin = {
blockStyleFn: (contentBlock) => {
if (contentBlock.getType() === 'blockquote') {
return 'superFancyBlockquote';
}
},
customStyleMap: {
'STRIKETHROUGH': {
textDecoration: 'line-through',
},
},
};
由于大多数插件都需要某种配置,因此建议您始终导出创建该对象的函数。 这与所有核心插件保持一致,并带来一致的开发人员体验。
export default createCustomPlugin = (config) => {
const blockStyleFn = (contentBlock) => {
if (contentBlock.getType() === 'blockquote') {
return 'superFancyBlockquote';
}
};
const customStyleMap = {
'STRIKETHROUGH': {
textDecoration: 'line-through',
},
};
return {
blockStyleFn: blockStyleFn,
customStyleMap: customStyleMap,
};
};
2、支持对象和钩子
插件接受Draft.js编辑器组件使用的所有标准属性。查看有关Draft.js文档的详细信息。常用属性:
- blockRendererFn
- keyBindingFn
- blockStyleFn
- blockRenderMap
- customStyleMap
- handleReturn
- handleKeyCommand
- handleBeforeInput
- handlePastedText
- handlePastedFiles
- handleDroppedFiles
- handleDrop
- onFocus
- onBlur
与原始属性相比有一个区别。所有函数都接收一个附加参数。此参数是一个包含以下内容的对象:
// PluginFunctions
{
getPlugins, // a function returning a list of all the plugins
getProps, // a function returning a list of all the props pass into the Editor
setEditorState, // a function to update the EditorState
getEditorState, // a function to get the current EditorState
getReadOnly, // a function returning of the Editor is set to readOnly
setReadOnly, // a function which allows to set the Editor to readOnly
getEditorRef, // a function to get the editor reference
}
除此之外,插件接受以下参数:
- initialize: (PluginFunctions) => void
- onChange: (EditorState, PluginFunctions) => EditorState
- willUnmount: (PluginFunctions) => void
- decorators: Array => void
- getAccessibilityProps: () => { ariaHasPopup: string, ariaExpanded: string }
2.1 initialize
当编辑器挂载时即可初始化插件
2.2 onChange
在编辑器的onChange触发之前,对state进行修改
2.3 willUnmount
通常用于清理
2.4 decorators
Draft.js运行通过装饰器初始化EditorState。许多插件依赖装饰器,因此将其合并到插件体系结构中。每个插件可以具有多个装饰器,并且所有的装饰器由插件编辑器组合。
装饰器包含strategy和component属性。
{
decorators: [
{
strategy: hashtagStrategy,
component: HashtagSpan,
},
],
}
如果要自己实现DraftDecoratorType接口,则可以将其包含在装饰器数组中与复合装饰器一起的位置。
有关DraftDecoratorType的实现示例,请参见draft-js-simpledecorator。这是一个混合装饰器数组的示例:
{
decorators: [
{
strategy: hashtagStrategy,
component: HashtagSpan,
},
new MyCustomDraftDecoratorType('...'),
],
}
2.5 getAccessibilityProps
在诸如@mentions或Emoji自动完成之类的极少数情况下,插件应该能够设置某些ARIA属性。
目前,这仅允许设置aria-has-popup和aria-expanded。如果您有其他建议,请告诉我们。
欢迎扫码关注作者公众号