如何将此Javascript代码重构为React?

时间:2018-11-03 20:42:05

标签: javascript reactjs

我有这个Javascript函数,它接受4个输入-房屋成本,预付款,贷款期限(年)和年利率,并计算抵押付款。将其重构为React组件的最佳方法是什么。我是状态和道具概念的新手,不知道如何重构它以使其成为最有效的组件。还是应该将其分解为几个首先要输入然后分别计算的输入?

   function calculatePayment() {

     var houseCost = parseFloat(document.getElementById("houseCost").value);
    var downPayment = parseFloat(document.getElementById("downPayment").value);

    var termOfLoan = parseFloat(document.getElementById("termOfLoan").value);

    var annualInterestRate = parseFloat(document.getElementById("annualInterestRate").value);
    var principal = houseCost - downPayment;
    var percentageRate = annualInterestRate / 1200;
    var lengthOfLoan = 12 * termOfLoan;
    var monthlyPayment = (principal * percentageRate) / (1 - (Math.pow((1 + percentageRate) , lengthOfLoan * -1)));
    monthlyPayment = monthlyPayment.toFixed(2);
    document.getElementById("payment").value = monthlyPayment;

};

1 个答案:

答案 0 :(得分:0)

您可以将其变成一个纯函数,可以用作带有props且没有状态的React组件。

function PaymentAmount(props) {
  const { houseCost, downPayment, termOfLoan, annualInterestRate } = props;
  const payment = (/* do math */);
  return payment;
}

然后将其渲染为某处(假设您使用jsx),就像...

<div>
  Payment amount:
  <PaymentAmount
    houseCost={/* some value */}
    downPayment={/* some value */}
    termOfLoan={/* some value */}
    annualInterestRate={/* some value */}
  />
</div>
  

还是应该将其分解成几个首先要输入然后分别计算的输入?

如果您认为输入内容属于此组件的职责范围,则可以考虑使用有状态组件。

class PaymentCalculator extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      houseCost: 0,
      downPayment: 0,
      termOfLoan: 0,
      annualInterestRate: 0
    };
    this.handleHouseCostChange.bind(this);
    this.handleDownPaymentChange.bind(this);
    this.handleTermOfLoanChange.bind(this);
    this.handleAnnualInterestRateChange.bind(this);
  }

  handleHouseCostChange(event) {
    this.setState({houseCost: event.currentTarget.value });
  }

  handleDownPaymentChange(event) {
    this.setState({ downPayment: event.currentTarget.value });
  }

  handleTermOfLoanChange(event) {
    this.setState({ houseCost: event.currentTarget.value });
  }

  handleAnnualInterestRateChange(event) {
    this.setState({ annualInterestRate: event.currentTarget.value });
  }

  render() {
    return (
      <div>
        <input onChange={this.handleHouseCostChange} />
        <input onChange={this.handleDownPaymentChange} />
        <input onChange={this.handleTermOfLoanChange} />
        <input onChange={this.handleAnnualInterestRateChange} />
        Payment amount:
        <PaymentAmount
          houseCost={this.state.houseCost}
          downPayment={this.state.downPayment}
          termOfLoan={this.state.termOfLoan}
          annualInterestRate={this.state.annualInterestRate}
        />
      </div>
    );
  }
}

如果您已在该项目中启动并运行React,那么Intro to React tutorial可能会使其足够快,从而能够对您的函数进行反应以使用React。