2017-12-24 45 views
0

입력이 제어되는 앱을 만들고 있습니다. 나는 특정 입력은 숫자 만 허용하려면 나는 그것을 달성하지만, 그들을 걸리는 것이 문자ReactJS - 글자로 숫자 키패드를 입력하고 있습니다.

이는 입력 (코드 범위는 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) 
      } 
     ); 
    } 
} 
+0

왜''를 사용하지 않을까요? – charlietfl

+0

나는 이상하게도 문자를 삽입 한 후 숫자 입력을 받아들이지 만 <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>

이것은 도움이 될 것입니다 !!!