简体   繁体   English

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

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

with React state it was easy to set new value which was condition for render some input and then focus to that input with state callback. 使用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 />
  }
}

Now when switching to Mobx it is not possible 现在,当切换到Mobx时是不可能的

@observable showInput = false;

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

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

This will fail, because React did not yet rerender component with input. 这将失败,因为React尚未使用输入重新渲染组件。 Is there any way how wait and detect when rerender is done? 有什么方法可以等待和检测何时完成重新渲染?

The callback in setState will run after the state is set and the component is re-rendered. setState的回调将在设置状态并重新呈现组件后运行。 MobX has no equivalent. MobX没有等效项。 So use this method to do the focus after React has re-rendered the UI. 因此,在React重新渲染UI之后,请使用此方法进行焦点。

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

To run code immediately after first render 首次渲染后立即运行代码

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

React set focus on input after render 渲染后对输入进行反应集中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM