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

标签 javascript reactjs state mobx

使用 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/

相关文章:

javascript - JavaScript 有没有办法在浏览器解析 HTML 时加载图像路径之前更改图像路径?

reactjs - 翻译 i18next on React can't find key

javascript - 无法将状态数组值传递给 DOM

reactjs - 如何处理 render 方法直到 redux 返回结果?

javascript:访问父函数的所有变量

javascript - React/Mobx - 组件正在重新渲染,但未调用 componentWillReceiveProps()

javascript - 在 Javascript 中删除带有变量名称的 options_for_select 项目

reactjs - React - 转发多个引用

node.js - 将 React/Node/Express 应用程序上传到 Heroku 后获取 "Failed to load resource: net::ERR_CONNECTION_REFUSED"

javascript - Reactjs - 对状态中的对象数组进行排序