react.js - 请问用react怎么输入数量和单价后总价就会计算出来
本文介绍了react.js - 请问用react怎么输入数量和单价后总价就会计算出来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
<td>
<input type="text"
name="num"
placeholder="数量"
defaultValue={$.readProp(om, 'num')}
onChange={foo.bind(null, i)}/>
</td>
<td>
<input type="text"
name="price"
placeholder="单价"
defaultValue={$.readProp(om, 'price')}
onChange={foo.bind(null, i)}/>
</td>
<td>
<input type="text"
name="totalPrice"
placeholder="总价"
defaultValue={$.readProp(om, 'totalPrice')}
onChange={foo.bind(null, i)}/>
</td>
解决方案
看也知道你的代码并非React领域了...jQuery的钱符号($)都出现了。
所以乾脆用refs,让存取DOM更直接,范例1:
class Calculator extends React.Component {
handleOnChang = () => {
this.textInputTotalPrice.value =
(+this.textInputNum.value) * (+this.textInputPrice.value)
}
render() {
return (
<table>
<tbody>
<tr>
<td>
<input
type="text"
name="num"
placeholder="数量"
defaultValue={0}
ref={(input) => { this.textInputNum = input }}
onChange={this.handleOnChange}
/>
</td>
<td>
<input
type="text"
name="price"
placeholder="单价"
defaultValue={0}
ref={(input) => { this.textInputPrice = input }}
onChange={this.handleOnChange}
/>
</td>
<td>
<input
type="text"
name="totalPrice"
placeholder="总价"
defaultValue={0}
ref={(input) => { this.textInputTotalPrice = input }}
/>
</td>
</tr>
</tbody>
</table>
)
}
}
不过这样失去了使用React的大部份意义,所以应该要用React的state(状态)来作值的运算才是,范例2:
class Calculator extends React.Component {
constructor() {
super()
// 初始值
this.state = {
num: 0,
price: 0,
totalPrice: 0,
}
}
handleOnChange = (e) => {
// 先取得目前的state中的记录值
let { num, price, totalPrice } = this.state
// 用name来区分不同的文字框输入
if (e.target.getAttribute('name') === 'num') {
num = e.target.value
} else {
price = e.target.value
}
// 加总
totalPrice = (+num) * (+price)
// 改变state值,文字框会随著更动
this.setState({
num,
price,
totalPrice,
})
}
render() {
return (
<table>
<tbody>
<tr>
<td>
<input
type="text"
name="num"
placeholder="数量"
value={this.state.num}
onChange={this.handleOnChange}
/>
</td>
<td>
<input
type="text"
name="price"
placeholder="单价"
value={this.state.price}
onChange={this.handleOnChange}
/>
</td>
<td>
<input
type="text"
name="totalPrice"
placeholder="总价"
value={this.state.totalPrice}
disabled
/>
</td>
</tr>
</tbody>
</table>
)
}
}
快快的写了一下,有试过应该是可以用的。
这篇关于react.js - 请问用react怎么输入数量和单价后总价就会计算出来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文