reactjs - 如何访问字段数组中的指定字段以计算小计
问题描述
我正在使用表单 ValueSelector 并且正在使用计算字段数组。当我使用这种语法时,我遇到了语法问题,但在执行时间上没有错误。
这是计算小计的公式:
const calculatedSubtotal =
(`detail[${this.props.index}].quantity`,`detail[${this.props.index}].product.price`) =
`detail[${this.props.index}].quantity` * `detail[${this.props.index}].product.price`
这是计算总数的公式:
const calculatedTotal = (`detail[${this.props.index}].subtotal`) = 0 +
`detail[${this.props.index}].subtotal`
当我执行这些行时,我遇到了语法问题。
Detail 是 fieldArray 的名称。
如何从字段数组中声明指定字段以进行计算?
怎么了?
这是我的 renderDetail 组件:
renderDetail = ({fields, meta: { error,submitFailed}}) => (
<dl>
<dt>
<button type="button" className= 'btn btn-primary'
onClick={() => fields.push()}>Add Detail</button>
{submitFailed && error && <span>{error}</span>}
</dt>
{ fields.map((item, index) =>
<dd key={index}>
<br></br>
<button className= 'btn btn-light mr-2'
type="button"
title="Remove detail"
onClick={() => { fields.remove(index)
if(fields.length == 0 || fields.length ===
undefined){
}
try{
for(let x in fields){
fields.remove(index)
let d = fields.selectedIndex;
if(fields.remove(index) && d >= 1 && d<
fields.length ){
fields.removeAll(index);
}
}
}catch{console.info("deletes Index")}
}}> Delete </button>
<h4>Item #{index + 1}</h4>
<Field
id={`${item}._id`}
name={`${item}.quantity`}
component= {NumberPicker}
placeholder= '...quantity'
label = "Quantity"
/>
<br></br>
<h3><b>Product</b></h3>
<Field
id={`${item}._id`}
name={`${item}.product.code`}
type="number"
component= {RenderFieldNumber}
placeholder='...Product's code'
label = "product's code"
/>
<Field
id={`${item}._id`}
name={`${item}.product.name`}
type="text"
component= {RenderField}
placeholder='...Product's name'
label = "product's name"
/>
<Field
id={`${item}._id`}
name={`${item}.product.price`}
component= {NumberPickerFloat}
placeholder= '...Price'
label = "Product's price"
/>
<br></br>
<h3><b>Subtotal</b></h3>
<Field
id={`${item}._id`}
name={`${item}.subtotal`}
component= {SubtotalWidget}
placeholder= '...subtotal'
label = "Subtotal"
/>
</dd>
)
}
{error && <dt className="error">{error}</dt>}
</dl>
);
在渲染方法中,我以这种方式访问 fieldArray:
<div>Detail:</div>
<FieldArray
name='detail'
component={this.renderDetail}
label='Detail'
/>
解决方案
您是否尝试使用箭头函数来计算值?
const calculatedSubtotal = () => detail[this.props.index].quantity * detail[this.props.index].product.price
const calculatedTotal = () => 0 + detail[this.props.index].subtotal
推荐阅读
- python - Python h5py swmr 模式:写入器打开文件时无法读取数据
- vue.js - Vue - 复制查询参数的内置方式
- sbt - 无法安装或卸载 SBT
- amazon-web-services - S3 存储桶不驻留在 VPC 中?
- vba - vba 英德版excel数据的不同格式
- python - 电话号码的 Python 正则表达式
- c# - 如何从复杂的完整路径字符串中找到 System.Type?
- django - 查看类 dispatch() 找不到方法?
- robotframework - 无法在机器人框架中使用“选择文件”关键字上传图像文件。如何使用机器人框架处理图像上传验证?
- python - 如何调整标签张量的大小,以便我可以在 tf.nn.sigmoid_cross_entropy_with_logits 中使用它