[英]React constrained input fields (e.g. number with min constraint) doesn't allow you to type in value comfortably
Consider this simple react component that has an input field, which I'd like to constrain to have a minimum value of 20:考虑这个具有输入字段的简单反应组件,我想将其限制为最小值为 20:
class InputTest extends React.Component {
constructor(props) {
super(props);
this.state = {
val: 20,
};
}
valChange = event => {
let newVal = event.target.value;
if (newVal >= 20) {
this.setState({
val: newVal,
});
}
};
render() {
return (
<div>
<input
type={'number'}
value={this.state.val}
onChange={this.valChange}
/>
</div>
);
}
}
Now everything more or less works fine with this, unless I try to type in a brand new number into the field.现在一切或多或少都可以正常工作,除非我尝试在该字段中输入一个全新的数字。
eg if I want to select the number currently in the field and overwrite it with lets say 243.例如,如果我想选择当前字段中的数字并用 243 覆盖它。
As I highlight the number and press the "2" key, the react component rejects number 2 as it is smaller then 20, and I am unable to comfortably type the number in.当我突出显示数字并按下“2”键时,反应组件拒绝数字 2,因为它小于 20,我无法轻松输入数字。
I am wondering if there already exists some kind of a solution to this.我想知道是否已经存在某种解决方案。
If not I could probably build something with some kind of a delayed constraint check.如果不是,我可能可以通过某种延迟约束检查来构建一些东西。
EDIT: I should have mentioned this, but I only decided to add the most simple example to make things clearer.编辑:我应该提到这一点,但我只是决定添加最简单的例子来使事情更清楚。 In my case I also had a slider bound to the input field, so I'd want change the slider position as the value inside input changes and vice versa.在我的情况下,我还有一个滑块绑定到输入字段,所以我想随着输入中的值的变化而改变滑块的位置,反之亦然。 So simply notifying the user won't work, as the slider's min and max values are what's constraining the input.所以简单地通知用户是行不通的,因为滑块的最小值和最大值限制了输入。
I ended up using a debounce function to delay the slider position change.我最终使用了去抖动功能来延迟滑块位置的变化。
Wrap your input
inside a form
and add the min
and ( max
if you want) attributes.将您的input
包裹在一个form
并添加min
和(如果需要,则为max
)属性。 Press Enter
or Submit
to see the notification (You can remove the button if you don't want it)按Enter
或Submit
以查看通知(如果您不想要该按钮,可以删除该按钮)
<form> <input type = "number" min = 20 /> <input type = "submit" value = "submit" /> </form>
And remove the condition in your valChange
function you don't need it anymore.并删除您不再需要的valChange
函数中的条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.