【问题标题】:Mobx and React. How to handle focus input after observable change?Mobx 和反应。可观察到的变化后如何处理焦点输入?
【发布时间】:2017-07-16 06:04:00
【问题描述】:

使用 React 状态很容易设置新值,该值是渲染某些输入的条件,然后通过状态回调聚焦到该输入。

handleToggleInput() {
  const showInput = !this.state.showInput
  this.setState({ showInput }, () => showInput && this.refs.input.focus())
}

render() {
  if(this.state.showInput) {
    <input ref="input" type="text />
  }
}

现在切换到 Mobx 是不可能的

@observable showInput = false;

handleToggleInput() {
  this.showInput = !this.showInput
  this.showInput && this.refs.input.focus()
}

render() {
  if(this.showInput) {
    <input ref="input" type="text />
  }
}

这将失败,因为 React 尚未使用输入重新渲染组件。 有什么方法可以等待和检测何时重新渲染完成?

【问题讨论】:

  • 非常有趣。如果您defer the focus,它会起作用。如果您不有条件地隐藏输入,则它可以在没有延迟的情况下工作。希望 MobX 专业人士能对此有所启发。
  • @Tholle 非常聪明!这可能现在可以正常工作,但是将来使用 React Fiber 或其他 React 实现可能会因为重新渲染调度而出现问题。

标签: javascript reactjs state mobx


【解决方案1】:

setState 中的回调将在设置状态并重新渲染组件后运行。 MobX 没有等价物。所以在 React 重新渲染 UI 之后使用这个方法来做焦点。

componentDidUpdate: function(prevProps, prevState){
   this.refs.input.focus(); 
},

在第一次渲染后立即运行代码

componentDidMount: function(){
   this.refs.input.focus(); 
},

React set focus on input after render

https://facebook.github.io/react/docs/react-component.html#componentdidupdate

【讨论】:

  • 也开始使用 ref 回调,如 StackOverflow 问题所示。不推荐使用ref="input"
  • 但是我不知道从“不显示”到“显示”的可观察过渡。 ComponentDidUpdate 可以由数百万其他原因触发。唯一的解决方案,但丑陋的一个是在处理程序中保留一些属性this._focusOnUpdate = showInput,然后在它的生命周期事件中反映。但正如我所说,这很丑:(
  • 如果你想要一个新出现的输入,为什么不为那个输入使用autofocus属性呢?
  • 自动对焦简洁明了,但是当我showInput 在第一次渲染时为真,但我不想在那里对焦时,它变得非常复杂。我最初的问题更笼统,如何(以任何方式)在可观察到的变化后做出反应以重新渲染。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-17
  • 2018-07-28
  • 1970-01-01
相关资源
最近更新 更多