2017-12-24 58 views
0

私の入力が制御されているアプリを作っています。私は数字だけを受け入れるように特定の入力をしたいと私はそれを達成しているが、それは文字としてそれらを取るためには、これを入力する(コード範囲が105から96である)ReactJS - 入力は数字キーを文字として受け取ります

をテンキー入力になりません。

<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) 
      } 
     ); 
    } 
} 
+0

なぜ単に 'を使用しないのですか? – charlietfl

+0

私はそれをやったが、不思議なことに、今はどんな入力があっても、文字o記号を挿入した後、数字入力を受け入れるが、<4条件は無視する。これは非常に意外でした。 – MarksASP

答えて

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>

これは助けるかもしれない!!!

関連する問題