【发布时间】: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