ReactJS - 输入将小键盘键作为字母

问题描述 投票:0回答:1

我正在制作一个可以控制输入的应用程序。我想要一个特定的输入只接受数字,我已经实现了它,但它不会采用小键盘输入,因为它将它们作为字母(代码范围是96到105)

这是输入:

<input onKeyDown = {(e) => this.handleChange(e)} type="text" value = {this.state.inputValue} />

我的功能:

handleChange(e){

    let value = this.state.inputValue;

    if(e.keyCode >= 48 && e.keyCode <= 57 && value.length < 4)
    {
        this.setState(
            {
                inputValue: value + String.fromCharCode(e.keyCode)
            }
        );
    }
    else if(e.keyCode == 8)
    {
        this.setState(
            {
                inputValue: value.substring(0, value.length - 1)
            }
        );
    }
}
javascript reactjs jsx numpad
1个回答
0
投票

class Test extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      inputValue: null,
    }
  }
  handleChange(e) {
    let value = this.state.inputValue

    if (((e.keyCode >= 48 && e.keyCode <= 57) ||
        (e.keyCode >= 96 && e.keyCode <= 105)) &&
        value &&
        value.toString().length < 4
       ) {
      this.setState({
        inputValue: parseInt(value + String.fromCharCode(e.keyCode), 10)
      })
    }  if (e.keyCode >= 48 && e.keyCode <= 57 && !value) {
      this.setState({
        inputValue: parseInt(String.fromCharCode(e.keyCode), 10)
      })
    } else if (e.keyCode === 8) {
      if(value) {
        const stringSliced = value.toString().substring(0, value.toString().length - 1)
        this.setState({
        inputValue: stringSliced === "" 
              ? null
              : parseInt(stringSliced, 10)                                          
                                                        
        })  
      }
      
    }
  }
  render() {
    console.log("this.state", this.state)
    return (
      <input
        onKeyDown={
        e => this.handleChange(e)
        }
        type="text"
        value={
          this.state.inputValue
        }
      />
    )
  }
}

ReactDOM.render(<Test />, document.getElementById("root"));
<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>
<div id="root">
</div>

这可能有帮助!!!

© www.soinside.com 2019 - 2024. All rights reserved.