我要实现的目标是,一旦选择了百分比,便要设置输入框的值。但是要计算该值,我需要purchasePrice的值。我尝试过访问onDownPaymentPercentChange函数中的PurchasePrice属性,但是没有用。我如何做到这一点?
export default class PurchaseInfo extends Component{
constructor(props){
super(props);
this.state ={
purchasePrice:'',
downPayment:'',
}
}
onPurchasePriceChange = (e) => {
this.setState({
purchasePrice: e.target.value
})
}
onDownPaymentPercentChange = (e) => {
console.log(e.target.value)
this.setState({
downPayment: e.target.value * this.purchasePrice
})
}
render(){
return(
<div>
<label>Purchase Price</label>
<br/>
<input id='PurchasePrice' required placeholder='$' onChange={this.onPurchasePriceChange}></input>
<br/>
<br/>
<label>Percentage of purchase price</label>
<br/>
<select onChange={this.onDownPaymentPercentChange}>
<option value='.035'>3.5%</option>
<option value='.05'>.5%</option>
</select>
<br/>
<br>
<label> Down Payment <label />
<br/>
<input required placeholder='$' value={this.state.downPayment}>
</input>
</div>
最佳答案
您正在尝试访问名为purchasePrice
的类属性而不是状态值。
onDownPaymentPercentChange = (e) => {
this.setState({
downPayment: e.target.value * this.purchasePrice // Problem is here
})
}
通过状态对象访问
purchasePrice
,如下所示:this.state.purchasePrice
。关于javascript - 如何将表单中的变量传递给React.js中的onclick函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59721222/