Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/458.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React组件中的onChange事件验证错误_Javascript_Reactjs - Fatal编程技术网

Javascript React组件中的onChange事件验证错误

Javascript React组件中的onChange事件验证错误,javascript,reactjs,Javascript,Reactjs,这看起来很直截了当,但我在React组件中的验证并没有按预期工作。显然,它应该只传递1到10之间的整数,但任何包含范围号的输入都会触发else部分的handleInput方法: class FormToRefresh extends React.Component { constructor(props) { super(props) this.state = {value: 1} this.handleInput = this.handleInput.bind(th

这看起来很直截了当,但我在React组件中的验证并没有按预期工作。显然,它应该只传递1到10之间的整数,但任何包含范围号的输入都会触发
else
部分的
handleInput
方法:

class FormToRefresh extends React.Component {
  constructor(props) {
    super(props)
    this.state = {value: 1}
    this.handleInput = this.handleInput.bind(this)
  } 

  handleInput(e) {
    let input = e.target.value
    const inputRange = [1,2,3,4,5,6,7,8,9,10]
    if(inputRange.includes(input)) {
      this.setState({value: input}) 
    }
    else {
      alert("Wrong input")
      this.setState({value: this.state.value})  
    }
  }

  render() {
    return (
      <div>
      <form onSubmit={this.handleSubmit}>            

      <input 
        type="text" 
        value={this.state.value} 
        onChange={this.handleInput} 
      />

      <button type="submit">
        Refresh
      </button>

      </form>
    </div>        

    )
  }
}
类FormToRefresh扩展了React.Component{
建造师(道具){
超级(道具)
this.state={value:1}
this.handleInput=this.handleInput.bind(this)
} 
手动输入(e){
让输入=e.target.value
常量输入范围=[1,2,3,4,5,6,7,8,9,10]
if(输入范围包括(输入)){
this.setState({value:input})
}
否则{
警报(“错误输入”)
this.setState({value:this.state.value})
}
}
render(){
返回(
刷新
)
}
}
这是因为:

const inputRange = [1,2,3,4,5,6,7,8,9,10]
if(inputRange.includes(input))
以数字表示的数组,但是
e.target.value
将是一个字符串,因为它是输入框的内容。试试这个:

const inputRange = [1,2,3,4,5,6,7,8,9,10]
if(inputRange.includes(parseInt(input)))
应首先将输入转换为整数。记住要进行错误处理,这是因为:

const inputRange = [1,2,3,4,5,6,7,8,9,10]
if(inputRange.includes(input))
以数字表示的数组,但是
e.target.value
将是一个字符串,因为它是输入框的内容。试试这个:

const inputRange = [1,2,3,4,5,6,7,8,9,10]
if(inputRange.includes(parseInt(input)))

应首先将输入转换为整数。并记住在
输入
节点上执行错误处理

字段返回
字符串中的值

因此,尝试将字符串解析为数字:

let input = parseInt(e.target.value, 10)

输入
节点上的
字段返回
字符串中的值

因此,尝试将字符串解析为数字:

let input = parseInt(e.target.value, 10)