[英]Text input blurs after focusing in Firefox in React
我有文字输入:
{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
为false。 通过单击按钮,我可以执行以下操作:
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有关。
这个问题与firefox本身而不是React的<input type="number">
的奇怪行为(换句话说就是错误)有关。 在新创建的 type="number"
元素上调用.focus()
之后,Firefox会立即触发onBlur
。 当然,您可以将type="number"
替换为type="number"
type="text"
,但这不是解决问题的好方法。
根据情况(或首选项),有两种选择。
this.inputRef.current.focus();
进入setTimeout ,就像这样setTimeout(() => this.inputRef.current.focus(), 100);
。 在创建输入之后100毫秒,该输入将变得集中。 对于这种情况,您需要组件状态下的其他属性,例如, initialized: false
。
接下来,您需要在onBlur
处理程序(或示例中的revertValue)中将initialized
设置为true ,由于我上面写的奇怪行为,此代码仅在firefox中有效。
if (!this.state.initialized) {
return this.setState({
initialized: true,
});
}
在最后一步,您需要在.focus()之后使用此代码为其他浏览器“重置”此属性。 请注意,这是一个异步调用。
this.setState(() => ({
initialized: true,
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.