【发布时间】:2020-04-11 06:23:11
【问题描述】:
我有一个contentEditable react 组件,它会根据各种状态变化进行更新。状态项包含文本框中的段落。这些是 React 组件。下面是 3 个段落的示例状态值。
相应的文本框可能如下所示:
到 React 组件的转换发生在单击按钮时。当我用新段落更新 HTML 状态项时,我有一些奇怪的行为。它再次追加新段落而不是替换:它应该始终输出 html 状态项中包含的内容。
看起来我现在有 5 个段落组件处于状态。但我没有,我应该只看到如下四项:
我的渲染方法只是一个通过状态中的 HTML 项的映射。这有点难以解释,但希望它是有道理的。我认为这与 React 如何比较组件有关?
相关代码:
// Method to update state with new HTML components
componentDidUpdate = prevProps => {
if (prevProps.isSubmitted !== this.props.isSubmitted) {
this.handleStateUpdate({
html: this.createHtml()
});
}
};
// createHTML function is something like this, I have excluded unimportant code
createHtml = () =>
this.props.paragraphDict.map((paragraph, key) => {
const flaggedWords = Object.keys(paragraph);
return (
<Paragraph key={key}>
{flaggedWords.map(wordId => (
<Word key={wordId} {...props} />
))}
</Paragraph>
);
});
// Render
render = () => {
const { html } = this.state;
return (
<StyledEditor
ref={this.el}
contentEditable={true}
suppressContentEditableWarning={true}
spellCheck={false}
onBlur={({ target }) => this.handleEditorBlur(target.innerHTML)}
>
{html && html.map(item => item)}
</StyledEditor>
);
};
【问题讨论】:
-
完成。这还有很多其他的部分,但我认为这是相关的逻辑。
-
if (prevProps.isSubmitted !== isSubmitted)-- 你的意思是if (prevProps.isSubmitted !== this.props.isSubmitted)吗?还是isSubmitted定义在其他地方? -
对不起,我愿意。我错误地删除了那部分。已更新。
标签: reactjs