gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:04:50 25 4
gpt4 key购买 nike

我正在尝试制作 if else 语句以允许用户在 TextArea 中仅键入整数,但我不知道该怎么做。这是我的代码:

应用类扩展 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>
);
}

类 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>
);
}

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

导出默认应用;

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

最佳答案

您可以使用 regex并有条件地改变状态。

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

关于javascript - ReactJS - 如何允许用户只输入整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45675988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com