使用 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();
},
React set focus on input after render
https://facebook.github.io/react/docs/react-component.html#componentdidupdate
关于javascript - Mobx 和 React。可观察到的变化后如何处理焦点输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42455026/