slatejs: renderElement 添加自定义的元素
Slate 允许您定义任何类型的自定义块,例如块引用、代码块、列表项等。
自定义 renderElement
<Editable
// Pass in the `renderElement` function.
renderElement={renderElement}
onKeyDown={event => {
if (event.key === '&') {
event.preventDefault()
editor.insertText('and')
}
}}
/>
先看一下默认的 renderElement
const DefaultElement = (props) => {
return <p {...props.attributes}>{props.children}</p>;
};
// Define a rendering function based on the element passed to `props`. We use
// `useCallback` here to memoize the function for subsequent renders.
const renderElement = (props) => {
switch (props.element.type) {
default:
return <DefaultElement {...props} />;
}
};
根据条件获取匹配的节点
const [ match ] = Editor.nodes(editor, {
match: (n) => n.type === "code",
});
将当前节点转化为新的类型
Transforms.setNodes(
editor,
{ type: match ? "paragraph" : "code" }
// { match: n => Editor.isBlock(editor, n) }
);
参考