2017-02-25 54 views
1

与React状态很容易设置新值,这是呈现某些输入的条件,然后使用状态回调将焦点集中到该输入。Mobx和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 /> 
    } 
} 

这将失败,因为输入做出反应还没有把重新呈现组件。 有什么办法可以等待和检测什么时候恢复?

+0

非常有趣。如果你[**推迟焦点**](http://jsbin.com/kuzariquce/edit?js,output),它就可以工作。如果你没有有条件地隐藏输入,它可以毫无延迟地工作。希望MobX专业人员能够对此发出一些启发。 – Tholle

+1

@Tholle非常聪明!这可能现在工作得很好,但是由于rerender调度,将来可能会出现React Fiber或其他React实现的问题。 – Schovi

回答

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

+0

也开始使用ref回调,如StackOverflow问题所示。使用'ref =“input”'已弃用。 – aitchnyu

+0

但是我不知道从“不显示”到“显示”的可观察转换。 ComponentDidUpdate可能由其他数百万种原因触发。唯一的解决方案,但丑陋的是在处理程序中保留一些属性'this._focusOnUpdate = showInput',然后在其中反映生命周期事件。但是,正如我所说它很丑陋:( – Schovi

+0

如果你想要一个新出现的输入,为什么不使用'autofocus'属性来输入? – aitchnyu