Mobx 和 React。可观察到的变化后如何处理焦点输入?

Mobx and React. How to handle focus input after observable change?

使用 React state 可以很容易地设置新值,该值是呈现某些输入的条件,然后使用状态回调关注该输入。

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 还没有重新渲染带有输入的组件。 有什么方法可以等待和检测何时重新渲染完成?

setState中的回调将在设置状态并重新渲染组件后运行。 MobX 没有等价物。所以在 React 重新渲染 UI.

之后使用这个方法做焦点
componentDidUpdate: function(prevProps, prevState){
   this.refs.input.focus(); 
},

到 运行 第一次渲染后立即编码

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

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