React 根据条件自动计算
1.输入框
<Item {...formItemProps} label="留房日期"> {getFieldDecorator('date', { rules: [{ required: true, message: '请选择留房日期!' }], }) (<RangePicker style={{ width: '66%', marginRight: '4%' }} value={date} onChange={this.setTotalPrice} />) } </Item> <Item {...formItemProps} label="单价"> {getFieldDecorator('unitPrice', { rules: [{ required: true, message: '请输入单价' }], })(<Input placeholder="请输入" value={unitPrice} onChange={this.setTotalPrice} />)} </Item> <Item {...formItemProps} label="间数"> {getFieldDecorator('roomNum')(<InputNumber value={roomNum} onChange={this.setTotalPrice} />)} </Item>
2.计算函数
/**
* 计算总价:保留几位小数
* 总价=单价[unitPrice]*留芳天数[date]*间数[roomNum]
* 留房天数=留房天数:(留房结束时间-留房开始时间)+1
*/
setTotalPrice = (e) => {
const {
form:{
setFieldsValue
}
} = this.props
let {
unitPrice,
date,
roomNum,
} = this.state
if(e.target){
if(e.target.id === 'unitPrice'){
unitPrice = e.target.value
}else{
roomNum = e.target.value
}
this.setState({
[e.target.id]: e.target.value
})
}else if(typeof(e) === 'number'){
roomNum = e
this.setState({
roomNum: e
})
}else{
const dateData = [e[0].format('YYYY-MM-DD'), e[1].format('YYYY-MM-DD')]
date = dateData
this.setState({
date: dateData
})
}
if(unitPrice === '' || unitPrice === null || date === [] || date === null || roomNum === '' || roomNum === null) {
this.setState({totalPrice: ''})
setFieldsValue({ totalPrice: '' })
return
}
const roomNumInt = parseInt(roomNum, 10)
const unitPriceFloat = parseFloat(unitPrice)
const leaveDayNum = getAllDate(date[0], date[1]).length
const totalPrices = (roomNumInt*unitPriceFloat*leaveDayNum).toFixed(2).toString()
this.setState({ totalPrice: totalPrices})
setFieldsValue({ totalPrice: totalPrices })
}