我如何在React js中将数字从输入转换为int

问题描述 投票:0回答:2
import React, { Component } from 'react'
export default class Ccomponent extends Component {
    constructor(props) {
        super(props)
        this.state = {
            first: 0,
            second: 0,
            Otv: 0
        };
        this.firstChange = this.firstChange.bind(this);
        this.secondChange = this.secondChange.bind(this);
        this.Otvet = this.Otvet.bind(this);
        this.ConvertToInt = this.ConvertToInt.bind(this);
    }
firstChange(event){
    this.setState({
        first: event.target.value
    });
    this.Otvet()
}
secondChange(event){
    this.setState({
        second: event.target.value
    });
    this.Otvet()
}
Otvet(event){   
    this.setState({
        Otv: this.state.first+this.state.second
    });
    this.ConvertToInt();
}
ConvertToInt(event){
    var a = this.state.first;
    var b = this.state.second;
    let v = a+b //i can try use parceInt, error - 'parceInt' is not defined  no-undef
    console.log(v);
}
    render() {
        console.log(this)
        return(
            <div>
               <input type='number' value = {this.state.first} onChange={this.firstChange}/>
               <input type='number' value = {this.state.second} onChange={this.secondChange}/>
               <h3>Summa: {this.state.first}+{this.state.second}</h3>
               <h1>Otvet: {this.state.Otv}</h1>
            </div>
        )
}}

我的输入以字符串格式将值发送到对象,如果 parceInt 不起作用,我如何将 str 转换为 int。 也许有办法获取 int 形式的值? 或者 React 有内部函数可以将字符串转换为整数?

javascript reactjs input type-conversion
2个回答
1
投票

parceInt()
拼写不正确。小错别字😅。它的拼写是
parseInt()
尝试一下。

例如,

let str = "123"
let num = parseInt(str)
console.log(num) // 123

0
投票

我尝试直接在输入字段中执行此操作,但不幸的是它给出了以下错误: 类型错误:setSalesItem.parseInt 不是函数

代码是: onChange={((e)=>{salesItem.parseInt(e.target.value)})}

我做错了什么吗?

提前致谢

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