[英]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.