entity - 有没有办法在 Draftjs 中添加牢不可破的实体?
问题描述
我正在使用 Draftjs 编辑器。我有一个装饰器,它通过正则表达式检测一些文本并生成一个自制组件。这是调用 API 并通过将初始文本替换为 API 的结果来返回结果。
我想让这个结果成为一个不可破坏、不可编辑的实体,但我不知道该怎么做。
这是我用来替换值的函数
/**
* Replace text in editor
*
* @param {Object} editorState - State of the editor
* @param {string} search - Search value
* @param {string} replaceValue - replacement value
*
* @returns {Object} Returns the new editorState with link removed
*/
static replace(editorState, search, replaceValue) {
if (typeof search === 'undefined' || search === null) {
return editorState;
}
const regex = new RegExp(escapeStringRegexp(search), 'g');
const blockMap = editorState.getCurrentContent().getBlockMap();
const selectionsToReplace = [];
blockMap.forEach((contentBlock) => (
findWithRegex(regex, contentBlock, (start, end) => {
const blockKey = contentBlock.getKey();
const blockSelection = SelectionState
.createEmpty(blockKey)
.merge({
anchorOffset: start,
focusOffset: end,
});
selectionsToReplace.push(blockSelection)
})
));
let contentState = editorState.getCurrentContent();
selectionsToReplace.forEach(selectionState => {
contentState = Modifier.replaceText(contentState, selectionState, replaceValue)
});
return draftEditorState.push(editorState, contentState);
}
我想要的是结果可以作为全局部分移动或删除并且不能更改。
谢谢你的帮助。
解决方案
我认为您正在寻找的是 Draftjs' entities
。假设您使用 应用实体IMMUTABLE
,它将被视为不可编辑,如果您尝试删除部分单词,则整个内容将被删除。
这是一个使用实体但使用预先标记的段的官方Draftjs 示例。我认为在你的情况下,它就像在里面做这样的事情一样简单findWithRegex
(还没有测试过,所以这可能是一种方法——只是想把这个想法传达出去):
let newContentState = editorState.getCurrentContent();
findWithRegex(regex, contentBlock, (start, end) => {
const blockKey = contentBlock.getKey();
const blockSelection = SelectionState
.createEmpty(blockKey)
.set("anchorOffset", start)
.set("focusOffset", end);
const searchEntity = content.createEntity(
"SEARCH", // type
"MUTABLE", // mutability <--
);
const entityKey = content.getLastCreatedEntityKey();
newContentState = Modifier.applyEntity(searchEntity, blockSelection, entityKey);
})
return EditorState.push(editorState, newContentState, "apply-search-styling");
推荐阅读
- c - 在 Visual Studio Code 中编译 C 程序时出错
- visual-studio-code - 无法在 monaco-editor 的模型配置中填写 rootUri 和 rootPath 字段
- pandas - 在 pandas 中将日期转换为 int
- go - GORM Database.First(&tableStruct, id) without deleted_at IS NULL
- google-analytics - 无法在 API 中获得适当数量的用户
- mongodb - MongoDB - 将嵌套数组中的数据类型更新为字符串到数字不起作用
- rest - 在 REST 中处理依赖 4XX
- javascript - Javascript 计算器 if 语句不起作用
- python - 选择最右边的列,在 Pandas DataFrame 中没有 nan 值
- .net - 如何修复 Azure devops 上的构建错误“使用来自文件 '--Assembly.snk' 的公钥的公钥签名输出错误——找不到文件”?