哪个组件需要键在重新渲染后保持焦点?

Which component needs keys to keep focus after rerender?

我被这个问题困扰了好几天,我已经浏览了 React.js - input losing focus when rerendering,其中列出了几个建议和解决方案,以解决第一次击键时失去注意力的问题 - 但我仍然没有设法解决它。此时我很恐慌,所以可能错过了明显的解决方案。

这是一个显示焦点丢失的代码框:https://codesandbox.io/s/fervent-tereshkova-bz1wz?file=/agenda.js

onChange = ({ value }) => {
    if (this.props.onChange) {
      // Check to see if the document value really has changed
      if (value.document !== this.state.value.document) {
        this.props.onChange(value);  //  <----- This line is ruining it for you
      }
    }
    this.setState({ value });
  };

指示的行给你毁了,我不明白你需要它做什么。 如果您想在状态真正改变时触发回调,您应该通过 componentWillUpdate(object nextProps, object nextState) 执行此操作,然后将 nextState.value.documentthis.state.value.document 进行比较,如下所示:

componentWillUpdate = (object nextProps, object nextState) => {
  if (nextState.value.document !== this.state.value.document)
    this.props.onChange(nextState.value);
}

...或者您可以使用 setState callback 在状态更新后触发代码:

onChange = ({ value }) => {
  var newDocValue = value.document;
  var oldDocValue = this.state.value.document;
  this.setState({ value }, () => {
    if (oldDocValue !== newDocValue)
      this.props.onChange(newDocValue);
  });
}

我个人会将整个组件重写为函数组件,因为我认为使用 useEffect 钩子可以更轻松地处理生命周期和变更反应。