ReactJS - 如何允许用户仅输入整数

Vla*_*rov 3 javascript if-statement reactjs

我正在尝试制作 if else 语句以允许用户仅输入整数,TextArea但我不知道如何操作。这是我的代码:

类 App 扩展了 React.Component {

constructor(props) {
    super(props)

    this.state = {
        currencyValue: '',
        currencyCode: 'USD',
        result: ''
    }
}

handleChangeCurrencyValue(event) {
    console.log('qwer ' + this)
    this.setState(Object.assign({}, this.state, {currencyValue: event.target.value}))
}

handleChangeCurrencyCode(event) {
    console.log('qwer ' + this)
    this.setState(Object.assign({}, this.state, {currencyCode: event.target.value}))
}

calculate(event){
    var obj = this 
    axios.get('http://localhost:8080/Currency/currency?currencyCode=' + this.state.currencyCode + '&currencyValue=' + this.state.currencyValue + '&responseType=json')
    .then(function(resp){
        console.log('RESULT: ', resp.data.result)
            obj.setState(Object.assign({}, obj.state, {result: resp.data.result}))
    })
    .catch(error => {
        console.log(error)
    });
}

render() {
    return (
        <div>
            <TextArea functionChangeValue={this.handleChangeCurrencyValue.bind(this)} value={this.state.currencyValue} />
            <ComboBox functionChangeCode={this.handleChangeCurrencyCode.bind(this)} value={this.state.currencyCode} />
            <p>
                <button onClick={this.calculate.bind(this)}>Calculate</button>
            </p>
            <div>{this.state.result}</div>
        </div>
    );
}
Run Code Online (Sandbox Code Playgroud)

}

类 TextArea 扩展 React.Component {

render() {
    return (
        <div>
            <h4>
                <div>Type value you want to exchange: </div>
                <input type='text' onChange={this.props.functionChangeValue}/>
                 {/* <div>Value of your currency is: {this.props.value}</div> */}
            </h4>
        </div>
    );
}
Run Code Online (Sandbox Code Playgroud)

}

类 ComboBox 扩展了 React.Component {

render() {
    return(
        <div>
            <h4>
                <div>Select your currency:</div>
                <select onChange={this.props.functionChangeCode}>
                <option>USD</option>
                <option>EUR</option>
                <option>GBP</option>
                </select>
                {/* <div>Your currency is: {this.props.value}</div> */}
            </h4>
        </div>
    );
}
Run Code Online (Sandbox Code Playgroud)

}

导出默认应用程序;

你能给我一个想法或一些例子吗?

mra*_*won 5

您可以使用正则表达式并有条件地更改状态。

   onChange(event){
      const regex = /^[0-9\b]+$/;
      const value = event.target.value;
      if (value === '' || regex.test(value)) {
         this.setState({ value })
      }
   }
Run Code Online (Sandbox Code Playgroud)