javascript - 如何修复增量按钮将数字添加到值的末尾而不是在 onChange 之后递增

标签 javascript reactjs

我正在尝试通过 React 处理按钮点击的增量。

令我感到困惑的是,递增会在数字的末尾添加一个值,而不是实际递增它,而递减则可以正常工作。例如,我通过键盘添加了一个值 30。然后,当我点击增量而不是 31 时,最终变成 301。

在我的父组件中我有:

state = {
    points: 0,
}  

updateInputValue = (event) => {
    this.setState({points : event.target.value})
}

handlePoints = (key) => {
    const { points } = this.state;

    if(key === 'increment')
        this.setState({ points: points + 1 })
    else
        points  > 0 && this.setState({ points: points - 1 })
};

在 child 身上:

<input
    type="number" 
    id="num_of_players" 
    name="Number of Players"
    min="0"   value= {this.props.points} onChange={evt => 
    this.props.updateInputValue(evt)}/>

<button
    width={`${BUTTON_WIDTH}px`} 
    fontSize={`${BUTTON_FONTSIZE}px`} 
    color='red' 
    onClick= {()=> this.props.handlePoints('increment')}><ImageContainer> 
    <Image><img src={ plusIconSVG } alt='plus button' /></Image> 
    </ImageContainer></button>

最佳答案

我认为问题在于它使用的是 plus 的字符串版本,这是连接。发生这种情况的原因是因为 event.target.value 变量是一个字符串。尝试用 parseInt 包装。

关于javascript - 如何修复增量按钮将数字添加到值的末尾而不是在 onChange 之后递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55986411/

相关文章:

javascript - 如何在 Javascript 中拆分字符串以应对特殊情况

reactjs - 父元素未获取子函数调用参数

javascript - 如何在 Antd 4 中使用 setFieldsValue 在 Form.List 中动态设置值?

reactjs - npm 错误! 401 Unauthorized : @babel/core@7. 1.0 使用创建新的 React 应用程序时

javascript - Yii2 复选框改变样式

javascript - Windows 10 Internet Explorer 15 版本中的 affix-bottom 问题

javascript - 将 const 添加到字符串中?

javascript - 在浏览器中更改输入后存储的值在哪里?

javascript - Reactjs onclick 不工作

javascript - 如何修复path.json不是一个函数