我有一个类型为 number
的输入字段。但是,如果我尝试输入 0,它就会忽略它。
怎么回事?
我的代码大致如下:
// render part of the component
return {
<div>
<input
type='number'
step='1'
min='0'
max='20'
value={this.state.myTargetsValue}
// @ts-ignore
onFocus={(evt) => evt.target.select()} // This selects all text on the first click
onChange={(evt) => this.handleChange(key, 'myTarget', evt.target.value)}
className='form-control'
/>
</div>
}
注意:handleChange 没有任何区别,出于测试目的,我从中删除了所有代码。
最佳答案
每当 0
表现得很滑稽时,通常会发现它落入了假装的陷阱。
在您的 handleChange()
函数中,您可能有一些代码试图按照这些行做一些事情:
if (newValue) {
this.setState({ key: newValue });
}
问题是 0
将无法通过这样的检查。相反,您需要显式检查不好的值:
if (![null, '', false].includes(newValue)) { }
是一种方法。这将检查它是否不是其他常见的错误值之一。还有其他方法,但基本思想是确保它不只是默认为正常的 JavaScript 行为。
关于javascript - 数字输入不会将 0 作为 React 应用程序中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49681176/