[英]Changing Material UI input VIA state creates infinite onfocus/onblur loop
So I have an input field that I want to display a temperature in. When the field is just being displayed I want it to show "49°F" and when the user focuses it I want it to show "49" with the stepper values. 因此,我有一个要在其中显示温度的输入字段。刚显示该字段时,我希望它显示为“ 49°F”,而当用户对其进行聚焦时,我希望它以步进值显示为“ 49” 。
So far this is what I have, my issue is on the handleBlur() function. 到目前为止,这是我所拥有的,我的问题是在handleBlur()函数上。 When onFocus is called, I change the state.type to be "number" which gives me the stepper, and forces a re-render.
调用onFocus时,我将state.type更改为“ number”,这使我有了步进器,并强制重新渲染。 Because it is re-rendered I lose focus on the element which then causes it to call onblur and change it back to a "text" type.
因为它是重新渲染的,所以我失去了对元素的关注,该元素随后导致它调用onblur并将其更改回“文本”类型。
The only way I have got it to semi-work is to disable the setState for the onFocus, but when I click out of my input it doesn't change it back to a type of "text". 我半完成的唯一方法是禁用onFocus的setState,但是当我单击输入时,它不会将其更改回“文本”类型。
I am not sure what to do here to fix this, I've tried multiple combinations of the blur/focus. 我不确定该如何解决此问题,我尝试了模糊/聚焦的多种组合。 I was under the assumption that if I assigned a key to the input, it wouldn't lose focus as it would update the component rather than re-create it, but I am guessing since I am changing the type it forces it to be recreated?
我当时的假设是,如果我为输入分配了一个键,它将不会失去焦点,因为它将更新组件而不是重新创建它,但是我猜测是因为我正在更改类型,因此它将强制重新创建它。 ? Not sure.
不确定。
Tldr: Changing input type from "number" to "text" VIA the state causes a loop between the onFocus and onBlur b/c the transition of the type via setState() forces it to be re-rendered and I lose focus on the element triggering onBlur. Tldr:将输入类型从“数字”更改为“文本”时,状态导致onFocus和onBlur b / c之间循环,通过setState()强制类型重新转换,而我失去对元素的关注触发onBlur。
Any help or guidance would be greatly appreciated! 任何帮助或指导将不胜感激!
handleBlur = () => {
cl("Handling the blur" + this.state.value)
this.setState({
type: "text",
})
//this.nameInput.type = "text";
};
onFocus = e => {
cl("Handling the focus " + this.state.value)
this.setState({
type: "number",
value: this.state.rawValue
});
this.nameInput.focus()
};
onChange = e =>{
this.setState({
value: e.target.value
})
}
render() {
return (
<div key="help">
<Input
key="temperature"
margin="dense"
value={this.state.value}
ref={(input) => {this.nameInput = input;}}
onChange={this.onChange}
onBlur={this.handleBlur}
onFocus={this.onFocus}
inputProps={{
step: this.step,
min: this.min,
max: this.max,
type: this.state.type
}}
/>
</div>
);
}
You can change input type without state. 您可以更改输入类型而无需状态。 First argument in event handler is SyntheticEvent, you can change input type like this
事件处理程序中的第一个参数是SyntheticEvent,您可以像这样更改输入类型
onFocus = e => {
e.currentTarget.type = "number";
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.