在数字输入旁边反应显示百分比,反之亦然

时间:2018-12-17 23:53:10

标签: javascript reactjs

我正在写一个房屋总成本的组件。 输入美元首付和首付百分比。当用户键入数字时,我想在输入的位置显示百分比,如果用户键入百分比,则显示相同的数字。

只是为了说明它,它看起来像这样:

总费用:200,000 首付:$ 0,百分比:0%

因此我们将百分比更改为5%,预付款会自动显示10,000美元-您就明白了。

我目前正在像这样获取输入值:

handleStateChange = (e) => {
        const { target: { name, value } } = e
        this.setState({ [name]: value })
    }

在输入内容内:

name="downPayment" value={ this.state.value } onChange={this.handleStateChange}

编写函数的最佳和有效方法是什么? handlePercentageChange()可以双向执行吗?

1 个答案:

答案 0 :(得分:1)

handleInputChange = (e) => {
  const { target: { name, value } } = e
  this.setState({ [name]: value })

  switch(name) {

    case 'downPaymentPercent' :
      const newAmount = value/100 * this.state.fullPrice // Assuming fullPrice set in state
      this.setState({ downPaymentAmount: newAmount })
      break
    case 'downPaymentAmount' :
      const newPercent = (value * 100) / this.state.fullPrice
      this.setState({ downPaymentPercent: newPercent })
      break
    default:
      break
  }
}


 // The 2 inputs
 name="downPaymentAmount" value={ this.state.downPaymentAmount } onChange={this.handleInputChange}
 name="downPaymentPercent" value={ this.state.downPaymentPercent } onChange={this.handleInputChange}
相关问题