1. decorator
1.1 作用:对block中的部分(或全部)文本做特殊渲染。
const { CompositeDecorator } = Draft;
const decorator = new CompositeDecorator([
{
strategy: (block: ContenBlock, callback: (start: number, end: numer) => void, contentState: ContentState) => {
block.findEntityRanges(
character => {
const entityKey = character.getEntity();
return (
entityKey !== null && block.getEntity(entityKey).getType() === 'ENTITY-TYPE'
);
},
callback
);
callback(start, end);
},
component: (props: {
contentState: ContentState;
entityKey: null | string;
blockKey: string;
start: number;
end: number;
decoratedText: string;
children: React.Children;
...
}) => <div />,
},
]);
EditorState.createWithContent(contentState, decorator)
EditorState.createEmpty(decorator)
2. blockRendererFn
2.1 作用:对指定block做特殊渲染。
function blockRendererFn(block: ContentBlock) {
if (block.getType() === 'atomic') {
return null | {
component: (props: {
block: ContentBlock;
blockProps: CustomProps;
selection: SelectionState;
contentState: ContentState;
decorator: CompositeDraftDecorator;
customStyleMap: Object;
...
}) => <div />,
editable?: boolean;
props?: CustomProps;
};
}
return null;
}
const { Editor } = Draft;
function MyComponent() {
return <Editor blockRendererFn={blockRendererFn} ... />;
}
3. 两者的区别
3.1 影响范围
- 两者都可以对整个block或block中的entity生效。
- blockRendererFn原则上只对整个block生效,但能拿到所有的block信息,所以也可以对不同entity做不同渲染。
- decorator原本只对block中的部分字符起效,但可以手动指定字符起始位置,所以也可以渲染整个block,而且组件里能拿到block的参数。
- decorator对block文本的装饰只限制于callback中指定的start->end间的字符,其他字符保持原样。
3.2 参数
- blockRendererFn 可以为渲染组件增加额外的自定义参数。
3.3 优先级
- blockRendererFn的优先级比decorator高。
- decorator会先进行匹配;如果之后的 blockRendererFn匹配成功(返回非null),decorator中对应的配置会无效。