gpt4 book ai didi

javascript - DraftJS 触发焦点内容更改?

转载 作者:行者123 更新时间:2023-11-29 16:46:21 26 4
gpt4 key购买 nike

我在页面上有一个编辑器和 save 按钮。我希望 save 按钮仅在有更改时出现(自上次保存以来)。因此,当您保存时,我设置了 this.setState({hasChanges: false}) 并在 onChange 函数中将 hasChanges 设置为 是的

一切正常。问题是当编辑器获得焦点时,编辑器将触发 onChange 事件(但内容尚未更改)。而且,这是根据他们的预期行为 documentation

The event listeners within the component will observe focus changes and propagate them through onChange as expected, so state and DOM will remain correctly in sync.

有什么方法可以知道 onChange 方法中的内容是否发生了变化,或者只是选择发生了变化?

最佳答案

我今天早些时候在 github 上发布了这个问题的答案,但我也会在这里添加它以供将来引用:

您说得对,每次 editorState 更改时都会调用 onChange。由于 editorState 同时包含 selectionStatecontentState,因此当有内容编辑和选择/焦点改变时它都会改变.

如果你想知道触发onChange方法的变化是在contentState中还是在selectionState中,你可以比较它们与他们的旧值(value)观:

function onChange(newState) {
const currentContentState = this.state.editorState.getCurrentContent()
const newContentState = newState.getCurrentContent()

if (currentContentState !== newContentState) {
// There was a change in the content
} else {
// The change was triggered by a change in focus/selection
}
}

现在,如果您知道更改发生在 contentState 中,您可以通过调用 newState.getLastChangeType() 获得更多信息。 .它应该返回任何 these values (除非您或您添加的某些插件创建了新的更改类型)。

关于javascript - DraftJS 触发焦点内容更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40911570/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com