React 将焦点设置在带有条件渲染的 input[type="number"] 上

die*_*ing 5 javascript firefox focus reactjs

在阅读了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>
  );
}
Run Code Online (Sandbox Code Playgroud)

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

2)requestAnimationFrame的解决方案:

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

render() {
  // same above
}
Run Code Online (Sandbox Code Playgroud)

该解决方案适用于 Chrome、IE11、Edge,但 Firefox 在尝试设置focus.

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

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

  render() {
   // same above
  }
Run Code Online (Sandbox Code Playgroud)

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

PS autoFocusattr 不适用于这种情况,这里我有条件渲染,所以需要在之后设置焦点click.

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

实时测试示例:codepen

Naz*_*riy 2

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;
Run Code Online (Sandbox Code Playgroud)

渲染到<MyInput/>你想要的地方。渲染后它将获得焦点。在 Safari、Chrome、Firefox 上测试。