react:如何从点击处理程序设置焦点

Joa*_*ous 6 html javascript reactjs redux

我的基于react-redux的表单有一个按钮,可以重置表单并将焦点移回第一个输入字段.
重置内容是直接的redux状态,但我在焦点上遇到了麻烦.

第一个字段上的autoFocus仅适用于初始渲染.有没有理智的方法重新触发它?

如果我需要使用显式的element.focus(),我应该从哪里调用它?我正在使用react-redux,但不是redux-forms.

And*_*yco 2

您是否保存了一些信息来知道哪个元素应该在页面加载时获得焦点?没有?那你为什么要稍后再这样做呢?

在分派操作后立即触发element.focus()- 您不需要 Redux 来实现此目的,也不需要 Redux 来存储此状态。

伪代码可能看起来像这样

onReset() {
  const action = {
    type: RESET_FORM,
  }
  dispatch(action);

  const element = getElement(); // propably read ref? Find element with [autoFocus] attribute in component?
  element.focus();
}
Run Code Online (Sandbox Code Playgroud)