我确信我做错了什么。但是,一个简单空html标记会导致convertFromHTML调用出现问题。
convertFromHTML("<p> </p>"); // returns null其中,作为:
convertFromHTML("<p>empty</p>"); // returns a valid object.有没有想过为什么会发生这种事?
发布于 2018-04-10 16:40:08
convertFromHTML("<p> </p>"); // returns null
我假设“return null”是字面意思,在这种情况下,更新到最新的draft-js版本应该可以解决这个问题。
下面是我运行的示例
create-react-app v1.5.2draft-js v0.10.5console.log(convertFromHTML('<p> </p>'))

有一个“有效”的对象,但contentBlocks属性为null,这意味着我们不能创建有效的ContentState,因为您将得到以下内容:
TypeError: Cannot read property 'contentBlocks' of null对为什么会发生这种情况有什么想法吗?
简而言之:节点需要文本。
深入解答:
以下所有代码都改编自撰写本文时的最新版本的draft-js source (提交4c4465f)。为简洁起见,省略了方法的某些部分。
此模块调用的方法是convertFromHTMLtoContentBlocks,它有几个主要步骤:
将来自string
contentBlocks object1)将字符串处理为DOM html由getChunkForHTML输出的方法处理,contentBlocks是从该输出创建的。
const convertFromHTMLtoContentBlocks = (
html: string,
DOMBuilder: Function = getSafeBodyFromHTML,
blockRenderMap?: DraftBlockRenderMap = DefaultDraftBlockRenderMap,
): ?{contentBlocks: ?Array<BlockNodeRecord>, entityMap: EntityMap} => {
const chunkData = getChunkForHTML( // processing our html string into chunkData
html,
DOMBuilder,
blockRenderMap,
DraftEntity,
);
// use the chunkData to create contentBlocks
const {chunk, entityMap} = chunkData;
const contentBlocks = convertChunkToContentBlocks(chunk);
return {
contentBlocks,
entityMap,
};
};检查getChunkForHTML,我们看到空格被修剪为<p></p>并传递给DOMBuilder。由DOMBuilder创建的DOM被genFragment转换成块,美化并作为chunk返回。
const getChunkForHTML = (
html: string,
DOMBuilder: Function,
blockRenderMap: DraftBlockRenderMap,
entityMap: EntityMap,
): ?{chunk: Chunk, entityMap: EntityMap} => {
html = html // the string is trimmed
.trim()
.replace(REGEX_CR, '')
.replace(REGEX_NBSP, SPACE)
.replace(REGEX_CARRIAGE, '')
.replace(REGEX_ZWS, '');
const safeBody = DOMBuilder(html); // create DOM from trimmed html
if (!safeBody) {
return null;
}
const fragment = genFragment(
entityMap,
safeBody, // use DOM to create blocks in genFragment
OrderedSet(),
'ul',
null,
workingBlocks,
-1,
blockRenderMap,
);
let chunk = fragment.chunk;
const newEntityMap = fragment.entityMap;
// rest of method
return {chunk, entityMap: newEntityMap};
};2)从字符串创建DOM如果我们在调试器中检查DOMBuilder方法(getSafeBodyFromHTML的别名) (source),我们会看到一个具有以下属性的DOM节点:
innerHTML: "<p></p>"
innerText:""3)从DOM生成块DOMBuilder的输出是作为safeBody的genFragment的参数。此方法将DOM树处理为多个块。由于我们的DOM不包含文本,因此从genFragment返回的对象具有属性:text: ""。

4)将数据块映射到contentBlocks
convertFromHTMLtoContentBlocks中的最后一个调用是
const contentBlocks = convertChunkToContentBlocks(chunk);
const convertChunkToContentBlocks = (chunk: Chunk): ?Array<BlockNodeRecord> => {
if (!chunk || !chunk.text || !Array.isArray(chunk.blocks)) {
return null;
}
// rest of method
}显然,此时chunk.text返回false,因此contentBlocks为null。
发布于 2018-09-04 16:52:58
我遇到了类似的问题,并使用draft-js v0.10.4解决了它。希望这也适用于您:)
https://stackoverflow.com/questions/49718171
复制相似问题