javascript - 如何为数组的动态输入对象创建handleChange函数
问题描述
我正在为我的个人项目创建一个发票生成器,以便更好地学习和理解 MERN 堆栈。我目前将此作为我的州的一部分。我目前将我的 className 链接到我的 CSS,因为我了解到可以操纵它来创建 handleChange 函数,所以我不确定是否需要完全改变它。我已经尝试使用索引,通过将每个对象映射到它的索引,但这只是令人困惑。
state = {
...
itemValues: [{
description: "",
rate: "",
quantity: "",
amount: "",
tax: ""
}],
...
}
这是我的映射值
itemValues.map((item, i) => {
let descId = `description-${i}`;
let rateId = `rate-${i}`;
let quanId = `quantity-${i}`;
let amonId = `amount-${i}`;
let taxId = `tax-${i}`;
return(
<div key={i} className="item-row">
<input
className="item item-description"
type="text"
id={descId}
name={descId}
placeholder="Item description"
data-id={descId}
onChange={this.handleChange('desc')}
/>
{/* */}
<input className="item item-rate"
type="text"
id={rateId}
name={rateId}
placeholder="Item rate"
data-id={rateId}
/>
{/* */}
<input className="item item-quantity"
id="item-quantity"
type="text"
placeholder="item quantity"
data-id={quanId}
/>
{/* */}
<input className="item item-amount"
id="item-amount"
type="text"
placeholder="item amount"
data-id={amonId}
/>
{/* */}
{this.state.taxation === "None" ? "" : <input class="item item-tax"
id="item-tax"
type="text"
placeholder="tax(%)"
data-id={taxId}
/>}
<input type='button' value='remove' onClick={this.removeClick}
/>
</div>
)
})
}
我不确定如何设置我的 handleChange 函数,以允许保存动态输入。
解决方案
由于是到全局组件的映射itemValuesComponent
,例如,您需要多个函数或索引以及将项目值设置为状态。
您可以尝试以下方法:
const handleChange = (location, property) => (e) => {
this.setState(prevState => ({
...prevState,
itemValues: [...prevState.itemValues.slice(0, location),
{
...prevState.itemValues[location],
[property]: e.target.value,
}
, ...prevState.itemValues.slice(location)]
}))
}
当你需要它时:
<input
...
onChange={this.handleChange(i,'description')}
/>
请让我知道这是否有效。
尝试使用 React Hooks,我很确定它会简化你的代码。
推荐阅读
- vue.js - NuxtJS + VueJS + 静态 JavaScript 游戏
- r - R:尝试对数据框中的日期范围进行子集化
- windows-subsystem-for-linux - 通过另一台机器访问 ext4.vhdx?
- sapui5 - 在本地和 WebIDE 中运行相同的 UI5 应用程序,使用真实数据和模拟数据
- java - 重试失败的功能文件
- php - Days of Stay 计数器与 php
- sql - sql中的OFFSET和FETCH NEXT:不能返回少于限制的记录数
- sql - 如何查阅具有重复参考值和不同状态的表格
- javascript - 记录不充分的 google 数据存储区 api 返回未定义的 transaction.get
- c - scanf 的第二个值没有改变