考虑number
类型的输入,我希望此数字输入仅允许用户输入一个正面,非零,整数(无小数)数字。使用min
和step
的简单实现如下所示:
class PositiveIntegerInput extends React.Component {
render () {
return <input type='number' min='1' step='1'></input>
}
}
ReactDOM.render(
<PositiveIntegerInput />,
document.getElementById('container')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<p>
Try to input a decimal or negative number or zero:
</p>
<div id="container"></div>
如果用户坚持只点击数字输入中的向上/向下箭头,上面的代码就可以正常工作了,但是一旦用户开始使用键盘,输入-42
,{3.14
之类的数字就没有问题。 {1}}和0
好的,让我们尝试添加一些onKeyDown
处理来禁止这个漏洞:
class PositiveIntegerInput extends React.Component {
constructor (props) {
super(props)
this.handleKeypress = this.handleKeypress.bind(this)
}
handleKeypress (e) {
const characterCode = e.key
if (characterCode === 'Backspace') return
const characterNumber = Number(characterCode)
if (characterNumber >= 0 && characterNumber <= 9) {
if (e.currentTarget.value && e.currentTarget.value.length) {
return
} else if (characterNumber === 0) {
e.preventDefault()
}
} else {
e.preventDefault()
}
}
render () {
return (
<input type='number' onKeyDown={this.handleKeypress} min='1' step='1'></input>
)
}
}
ReactDOM.render(
<PositiveIntegerInput />,
document.getElementById('container')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<p>
Try to input a decimal or negative number or zero:
</p>
<div id="container"></div>
现在一切似乎都按预期工作了。但是,如果用户突出显示文本输入中的所有数字,然后使用0
对此选择进行输入,则输入将允许0
作为值输入。
要解决此问题,我添加了一个onBlur
函数,用于检查输入值是否为0
,如果是,则将其更改为1
:
class PositiveIntegerInput extends React.Component {
constructor (props) {
super(props)
this.handleKeypress = this.handleKeypress.bind(this)
this.handleBlur = this.handleBlur.bind(this)
}
handleBlur (e) {
if (e.currentTarget.value === '0') e.currentTarget.value = '1'
}
handleKeypress (e) {
const characterCode = e.key
if (characterCode === 'Backspace') return
const characterNumber = Number(characterCode)
if (characterNumber >= 0 && characterNumber <= 9) {
if (e.currentTarget.value && e.currentTarget.value.length) {
return
} else if (characterNumber === 0) {
e.preventDefault()
}
} else {
e.preventDefault()
}
}
render () {
return (
<input
type='number'
onKeyDown={this.handleKeypress}
onBlur={this.handleBlur}
min='1'
step='1'
></input>
)
}
}
ReactDOM.render(
<PositiveIntegerInput />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<p>
Try to input a decimal or negative number or zero:
</p>
<div id="container"></div>
有没有更好的方法来实现这种标准的数字输入? 为输入写入所有这些开销似乎非常疯狂,只允许正数,非零整数......必须有更好的方法。
答案 0 :(得分:1)
这就是数字输入的工作原理。要简化代码,您可以尝试使用validity state(如果您的目标浏览器支持它)
onChange(e) {
if (!e.target.validity.badInput) {
this.setState(Number(e.target.value))
}
}
答案 1 :(得分:1)
这是React Bootstrap中的数字微调器植入。它仅接受正整数,您可以设置最小值,最大值和默认值。
class NumberSpinner extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
oldVal: 0,
value: 0,
maxVal: 0,
minVal: 0
};
this.handleIncrease = this.handleIncrease.bind(this);
this.handleDecrease = this.handleDecrease.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleBlur = this.handleBlur.bind(this);
}
componentDidMount() {
this.setState({
value: this.props.value,
minVal: this.props.min,
maxVal: this.props.max
});
}
handleBlur() {
const blurVal = parseInt(this.state.value, 10);
if (isNaN(blurVal) || blurVal > this.state.maxVal || blurVal < this.state.minVal) {
this.setState({
value: this.state.oldVal
});
this.props.changeVal(this.state.oldVal, this.props.field);
}
}
handleChange(e) {
const re = /^[0-9\b]+$/;
if (e.target.value === '' || re.test(e.target.value)) {
const blurVal = parseInt(this.state.value, 10);
if (blurVal <= this.state.maxVal && blurVal >= this.state.minVal) {
this.setState({
value: e.target.value,
oldVal: this.state.value
});
this.props.changeVal(e.target.value, this.props.field);
} else {
this.setState({
value: this.state.oldVal
});
}
}
}
handleIncrease() {
const newVal = parseInt(this.state.value, 10) + 1;
if (newVal <= this.state.maxVal) {
this.setState({
value: newVal,
oldVal: this.state.value
});
this.props.changeVal(newVal, this.props.field);
};
}
handleDecrease() {
const newVal = parseInt(this.state.value, 10) - 1;
if (newVal >= this.state.minVal) {
this.setState({
value: newVal,
oldVal: this.state.value
});
this.props.changeVal(newVal, this.props.field);
};
}
render() {
return ( <
ReactBootstrap.ButtonGroup size = "sm"
aria-label = "number spinner"
className = "number-spinner" >
<
ReactBootstrap.Button variant = "secondary"
onClick = {
this.handleDecrease
} > - < /ReactBootstrap.Button> <
input value = {
this.state.value
}
onChange = {
this.handleChange
}
onBlur = {
this.handleBlur
}
/> <
ReactBootstrap.Button variant = "secondary"
onClick = {
this.handleIncrease
} > + < /ReactBootstrap.Button> < /
ReactBootstrap.ButtonGroup >
);
}
}
class App extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
value1: 1,
value2: 12
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(value, field) {
this.setState({ [field]: value });
}
render() {
return (
<div>
<div>Accept numbers from 1 to 10 only</div>
< NumberSpinner changeVal = {
() => this.handleChange
}
value = {
this.state.value1
}
min = {
1
}
max = {
10
}
field = 'value1'
/ >
<br /><br />
<div>Accept numbers from 10 to 20 only</div>
< NumberSpinner changeVal = {
() => this.handleChange
}
value = {
this.state.value2
}
min = {
10
}
max = {
20
}
field = 'value2'
/ >
<br /><br />
<div>If the number is out of range, the blur event will replace it with the last valid number</div>
</div>);
}
}
ReactDOM.render( < App / > ,
document.getElementById('root')
);
.number-spinner {
margin: 2px;
}
.number-spinner input {
width: 30px;
text-align: center;
}
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/react-bootstrap@next/dist/react-bootstrap.min.js" crossorigin></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css" crossorigin="anonymous">
<div id="root" />
答案 2 :(得分:0)
如果您使用组件状态中的值作为受控输入,则可以阻止更新状态onChange(如果它不符合您的条件)。 e.g。
class PositiveInput extends React.Component {
state = {
value: ''
}
onChange = e => {
//replace non-digits with blank
const value = e.target.value.replace(/[^\d]/,'');
if(parseInt(value) !== 0) {
this.setState({ value });
}
}
render() {
return (
<input
type="text"
value={this.state.value}
onChange={this.onChange}
/>
);
}
}
答案 3 :(得分:0)
这不是一个反应问题,而是一个html问题,你可以在这里看到https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number,我已经做了一个无状态的例子,你可以在这里看到 https://codesandbox.io/s/l5k250m87