1. decorator
1.1 作用:對(duì)block中的部分(或全部)文本做特殊渲染。
// 創(chuàng)建
const { CompositeDecorator } = Draft;
const decorator = new CompositeDecorator([
{
// 從block中的text截取出[start,end]的文本用component組件渲染;通常用于從block中選出某個(gè)entity對(duì)應(yīng)的[start,end]來(lái)用component渲染;
strategy: (block: ContenBlock, callback: (start: number, end: numer) => void, contentState: ContentState) => {
/** 案例1: 選取某個(gè)entity做特殊渲染 start **/
// ContentBlock.findEntityRanges(filterFn, callback):遍歷block中的entity,并將滿(mǎn)足條件的entity的[start,end]作為參數(shù)調(diào)用callback
block.findEntityRanges(
character => {
const entityKey = character.getEntity();
return (
entityKey !== null && block.getEntity(entityKey).getType() === 'ENTITY-TYPE'
);
},
callback
);
/** 案例1: 選取某個(gè)entity做特殊渲染 end **/
/** 案例2: 手動(dòng)指定[start,end] start **/
callback(start, end);
/** 案例2: 手動(dòng)指定[start,end] end **/
},
component: (props: {
contentState: ContentState;
entityKey: null | string;
blockKey: string;
start: number;
end: number;
// block文本的[start,end]部分
decoratedText: string;
// 被選中的文本用span標(biāo)簽包裹
children: React.Children;
...
}) => <div />,
},
]);
// 使用
EditorState.createWithContent(contentState, decorator)
// 或
EditorState.createEmpty(decorator)
2. blockRendererFn
2.1 作用:對(duì)指定block做特殊渲染。
// 創(chuàng)建
function blockRendererFn(block: ContentBlock) {
// 過(guò)濾block
if (block.getType() === 'atomic') {
// 如果返回null會(huì)按原內(nèi)容渲染;
return null | {
component: (props: {
block: ContentBlock;
blockProps: CustomProps;
selection: SelectionState;
contentState: ContentState;
decorator: CompositeDraftDecorator;
customStyleMap: Object;
...
}) => <div />,
// 是否可變忠聚,會(huì)在殼子上加一個(gè)contenteditable="true|false" 屬性
editable?: boolean;
// 自定義傳入組件的數(shù)據(jù)
props?: CustomProps;
};
}
return null;
}
// 使用
const { Editor } = Draft;
function MyComponent() {
return <Editor blockRendererFn={blockRendererFn} ... />;
}
3. 兩者的區(qū)別
3.1 影響范圍
- 兩者都可以對(duì)整個(gè)block或block中的entity生效。
- blockRendererFn原則上只對(duì)整個(gè)block生效唱捣,但能拿到所有的block信息两蟀,所以也可以對(duì)不同entity做不同渲染。
- decorator原本只對(duì)block中的部分字符起效震缭,但可以手動(dòng)指定字符起始位置赂毯,所以也可以渲染整個(gè)block,而且組件里能拿到block的參數(shù)拣宰。
- decorator對(duì)block文本的裝飾只限制于callback中指定的start->end間的字符党涕,其他字符保持原樣。
3.2 參數(shù)
- blockRendererFn 可以為渲染組件增加額外的自定義參數(shù)巡社。
3.3 優(yōu)先級(jí)
- blockRendererFn的優(yōu)先級(jí)比decorator高膛堤。
- decorator會(huì)先進(jìn)行匹配;如果之后的 blockRendererFn匹配成功(返回非null)晌该,decorator中對(duì)應(yīng)的配置會(huì)無(wú)效肥荔。