我正在尝试将动态字段添加到React JS表中,每次用户从下拉列表中选择产品时,该表都会获得一个新行,然后该行必须具有三个动态输入字段,我无法弄清楚如何管理其价值和onChange。 附带代码。
状态管理代码。
this.state = {
quantity: [],
costPrice: [],
total: [],
key: 0,
supplierId: "",
productId: "",
addedProducts: []
};
componentWillReceiveProps(nextProps) {
if (nextProps.product.productId > 0) {
let quantity = [...this.state.quantity, "1"];
//quantity.concat("0");
if (this.state.key == 0) {
this.setState({
addedProducts: this.state.addedProducts.concat(nextProps.product),
quantity: quantity
});
} else {
this.incrementKey();
this.setState({
addedProducts: this.state.addedProducts.concat(nextProps.product),
quantity: quantity
});
}
}
}
incrementKey() {
this.setState(state => {
return { key: state.key + 1 };
});
}
onChange(event, key) {
const obj = event.target.value;
alert(this.state.quantity.length);
if ([event.target.name] == "quantity") {
//var total = event.target.value * this.state.costPrice;
let quantity = [...this.state.quantity];
quantity[key] = obj;
this.setState({ quantity });
} else if ([event.target.name] == "costPrice") {
var total = this.state.quantity * event.target.value;
}
// this.setState({ [event.target.name]: event.target.value, total: total });
}
视图部分的代码
{addedProducts.map(object => (
<TableRow key={object.productId}>
<TableCell>{object.sku}</TableCell>
<TableCell>{object.productName}</TableCell>
<TableCell>
<TextField
id={"quantityText" + object.sku}
name="quantity"
value={quantity[0]}
style={{ width: "60px" }}
onChange={e => onChange(e, 0)}
inputProps={{ "aria-label": "bare" }}
/>
</TableCell>
<TableCell>
<TextField
id="costPriceText"
name={"costPrice" + object.sku}
value={costPrice}
style={{ width: "70px" }}
onChange={onChange}
inputProps={{ "aria-label": "bare" }}
/>
</TableCell>
<TableCell>
<TextField
id="totalText"
name={"total" + object.sku}
value={total}
style={{ width: "80px" }}
onChange={onChange}
inputProps={{ "aria-label": "bare" }}
/>
</TableCell>
</TableRow>
))}
</TableBody>