【发布时间】:2021-10-04 22:57:33
【问题描述】:
我正在将数据映射到 React 表单中的字段 A(产品字段)下拉选择选项。我想用字段 A 中选择的产品数量自动填充字段 B(价格字段)。 我可以列出字段 A 的产品选项。 在字段 A 中选择一个选项后,如何填充字段 B
下面是我的反应代码
constructor(props) {
super(props)
this.state = {
products: [],
}
}
handleItemNameChange(event) {
console.log(event.target.value);
console.log(this.state.products);
const selectedProduct = this.state.products.find(product =>
product.id === event.target.value);
this.setState({item_name: event.target.value, item_price:
selectedProduct.price });
}
handleItemPriceChange(event) {
this.setState( { ...this.state, item_price: event.target.value });
}
{/**** Field 1 ******/}
<Field className="form-control form-control-sm" name="item_name" component="select" type="select"
onChange={this.handleItemNameChange}>
{products.map((product) =>
<option key={product.id} value={product.id}>
{ product.name}
</option>
)}
</Field>
{/**** Field 2 ******/}
<Field className="form-control form-control-sm" name="item_price" type="text" onChange={this.handleItemPriceChange} />
{/**** end ******/}
Find Console log results images here. "16" is the Selected Product and the rest are all the listed products image 2
【问题讨论】:
-
将值传递给字段 2
标签: arrays reactjs forms field