【问题标题】:Text input blurs after focusing in Firefox in React在 React 中的 Firefox 中聚焦后文本输入模糊
【发布时间】:2018-10-08 09:30:41
【问题描述】:

我有一个文本输入:

{this.state.showInput 
    && (<input
        type="number"
        min="0"
        max="5"
        onKeyPress={this.onPressKey}
        onChange={this.onChangeHandler}
        onBlur={e => this.revertValue(e)}
        defaultValue={this.props.initialMark}
        ref={this.inputRef}
    />)
}

默认情况下showInput 为假。然后点击一个按钮:

this.setState({ showInput: true }, () => {
    if (this.inputRef.current)
        this.inputRef.current.focus();
});

使用 onBlur 我将 showInput 的值恢复为 false:

revertValue(e) {
    e.target.value = this.props.initialMark;
    this.setState({ showInput: false });
}

问题是为什么在触发 onFocus 后我看到模糊被触发,所以我的输入没有出现?如何避免这种行为?

这仅与 Firefox 有关。

【问题讨论】:

标签: javascript reactjs firefox


【解决方案1】:

此问题与&lt;input type="number"&gt; 本身而不是React 中的&lt;input type="number"&gt; 的奇怪行为(换句话说,错误)有关。在.focus() 使用type="number"新创建的元素 上调用后,Firefox 立即触发onBlur。当然您可以将type="number" 替换为type="text",但这不是解决问题的好方法。

根据情况(或偏好),有两种选择。

Click here to see demos.

  1. 异步。只需将您的 this.inputRef.current.focus(); 包装到 setTimeout 中,例如 setTimeout(() =&gt; this.inputRef.current.focus(), 100);。并且在创建输入 100 毫秒后,该输入获得焦点。
  2. 或者同步,我更喜欢这个。

对于这种情况,您需要在组件状态中添加其他属性,例如initialized: false

接下来,您需要在onBlur 处理程序中将initialized 设置为true(或在您的示例中为revertValue),此代码仅适用于Firefox,因为奇怪的行为,我在上面写过。

if (!this.state.initialized) {
  return this.setState({
    initialized: true,
  });
}

在最后一步,您需要在 .focus() 之后使用此代码为其他浏览器“重置”此属性。请注意,这是一个异步调用。

this.setState(() => ({
  initialized: true,
}));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 2021-11-16
    • 2011-10-23
    • 2016-04-12
    • 1970-01-01
    • 2013-11-08
    相关资源
    最近更新 更多