Ali*_*ter 3 javascript reactjs draftjs
因此,我插入的内容越多(在大约 20 个装饰器替换之后),我的 Draft-js 编辑器就会变得非常慢(hacky)。我猜测这种行为是由于装饰器使用正则表达式检查整个编辑器内容,并在每次状态更改时用表情符号组件替换匹配项。我还为正则表达式找到的每个匹配创建实体,我通过使用编辑器状态作为道具来装饰组件来实现这一点。有没有办法让它更快?这是我的装饰器:
{
strategy: emojiStrategy,
component: decorateComponentWithProps(RenderEmoji, {
getEditorState: this.getEditorState,
setEditorState: this.onChange
})
}
Run Code Online (Sandbox Code Playgroud)
这是我的表情符号策略:
function emojiRegexF(regex, contentBlock, callback, contentState) {
const text = contentBlock.getText();
let matchArr, start;
while ((matchArr = regex.exec(text)) !== null) {
start = matchArr.index;
callback(start, start + matchArr[0].length);
}
}
function emojiStrategy(contentBlock, callback, contentState) {
emojiRegexF(EMOJI_REGEX, contentBlock, callback, contentState);
}
Run Code Online (Sandbox Code Playgroud)
这是我的 RenderEmoji 组件:
const RenderEmoji = props => {
const contentBlock = props.children[0].props.block;
const emojiKey = contentBlock.getEntityAt(props.children[0].props.start);
const emojiShortName = props.decoratedText;
if (!emojiKey) {
setEntity(props, emojiShortName);
}
return (
<Emoji emoji={emojiShortName} set="emojione" size={24}>
{props.children}
</Emoji>
);
};
Run Code Online (Sandbox Code Playgroud)
这是我的 setEntity 函数,用于设置匹配的实体:
function setEntity(props, emojiShortName) {
const editorState = props.getEditorState();
const contentstate = editorState.getCurrentContent();
const contentStateWithEntity = contentstate.createEntity(
"emoji",
"IMMUTABLE",
{
emojiUnicode: emojiShortName
}
);
const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
const oldSelectionState = editorState.getSelection();
const selectionState = oldSelectionState.merge({
focusOffset: props.children[0].props.start + props.decoratedText.length,
anchorOffset: props.children[0].props.start
});
const newContentState = Modifier.applyEntity(
contentstate,
selectionState,
entityKey
);
const withBlank = Modifier.replaceText(
newContentState,
selectionState,
emojiShortName + " ",
null,
entityKey
);
const newEditorState = EditorState.push(
editorState,
withBlank,
"apply-entity"
);
props.setEditorState(newEditorState);
}
Run Code Online (Sandbox Code Playgroud)
有什么办法可以优化这个吗?谢谢
我不确定这是否是任何实际性能问题的根源,但有两件事看起来很有趣:
\n\nsetEntity在装饰器渲染期间更改编辑器状态(通过)。渲染函数应该是纯粹的。我想您会进行这种类型的处理,因为表情符号可能是通过复制粘贴或某种本机表情符号选择器插入的。更好的方法是:
\n\nsetEntity逻辑作为 \xe2\x80\x93 的一部分。onChangeconst emojiStrategy = (contentBlock, callback, contentState) => {\n contentBlock.findEntityRanges(character => {\n const entityKey = character.getEntity();\n return (\n entityKey !== null &&\n contentState.getEntity(entityKey).getType() === \'emoji\'\n );\n }, callback);\n};\nRun Code Online (Sandbox Code Playgroud)\n\n那么你的装饰器组件将不需要在渲染期间更新编辑器状态。您也可能不需要decorateComponentWithProps再使用。
现在回到性能\xe2\x80\x93\xc2\xa0,让您确定如何改进它的最佳方法是分析您的应用程序。您将能够准确判断击键过程中渲染需要时间的内容,然后追踪问题。
\n| 归档时间: |
|
| 查看次数: |
1873 次 |
| 最近记录: |