【问题标题】:React set focus on input[type="number"] with conditional render使用条件渲染将焦点设置在 input[type="number"] 上
【发布时间】:2018-03-13 12:40:56
【问题描述】:

在阅读React set focusReact focus with timeout 之后,我仍然有点困惑在输入上设置focus 的正确跨浏览器选项是什么。

我遇到了条件渲染输入的问题,在 table 中渲染后可能有焦点,其中 input 放置在 td 中。

1)componentDidUpdate解决方案:

//...
componentDidUpdate() {
  this.input && this.input.focus();
}

render() {
  const show = this.state.isShown;

  return (
    <td className="editable">
      {!show ? (
        <input
          type="number"
          ref={(input) => { this.input = input }}
          value={this.state.value}
          onBlur={this.save}
          onKeyPress={e =>
            e.which === 13 || e.keyCode === 13 ? this.save() : null}
      />
    ) : (
        <span onClick={this.onTdClick}>{this.props.name}</span>
      )}
    </td>
  );
}

此解决方案适用于 Chrome、IE11、Edge,但不适用于最新的 Firefox(点击span 后不出现输入事件。

2)requestAnimationFrame的解决方案:

//...
componentDidUpdate() {
  if (!this.state.isShown) {
    requestAnimationFrame(() => {
      this.input && this.input.focus();
    })
  }
}

render() {
  // same above
}

此解决方案适用于 Chrome、IE11、Edge,但 Firefox 在尝试设置 focus 时仍然不显示输入。

3)setTimeout(callback, n)的解决方案:

  //...
  componentDidUpdate() {
    if (!this.state.isShown) {
      setTimeout(() => {
        this.input && this.input.focus()
      }, 50);
    }
  }

  render() {
   // same above
  }

这个案例适用于 Chrome、IE11、Edge 和(最后)Firefox,但似乎这是最“丑陋”的一个。

附: autoFocus attr 不适合这种情况,这里我有条件渲染,所以需要在click.之后设置焦点

所以,我的问题是:我们是否有正确的方法来解决此问题,无需为 Firefox 设置 setTimeout

现场测试示例:codepen

【问题讨论】:

    标签: javascript reactjs firefox focus


    【解决方案1】:
    import React from 'react';
    
    const MyInput = React.createClass({
    
        componentDidMount(){
            this.elem.focus();
        },
    
        render(){
            return(
                <input
                    ref={(elem) => {this.elem = elem}}
                    type="text"
                />
            );
        }
    });
    export default MyInput;
    

    在你想要的地方渲染&lt;MyInput/&gt;。渲染后它将成为焦点。在 Safari、Chrome、Firefox 上测试。

    【讨论】:

    • 感谢您的建议。测试了您的解决方案,实际上这在 Firefox/etc 中适用于input["text"],但不适用于input["number"]。 (Firefox 甚至会显示输入)codepen
    猜你喜欢
    • 2018-10-05
    • 2013-01-17
    • 2014-01-13
    • 2023-03-28
    • 2011-11-08
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    相关资源
    最近更新 更多