下面是字段数组的初始化:
const { fields, append, remove } = useFieldArray({
control, // control props comes from useForm (optional: if you are using FormContext)
name: "items", // unique name for your Field Array
rules: {
required: "Please append at least 1 item"
}
});
动态形式:
{fields.map((field, i) =>
<div key={field.id} tw="grid grid-rows-2 grid-cols-[64px_100px_100px_auto] tablet:flex tablet:flex-row gap-x-6 gap-x-4 gap-y-4 mb-4">
<div tw="flex flex-col col-span-4 tablet:w-[220px]">
<label htmlFor="itemName" tw="text-secondary">Item Name</label>
<StyledInput type="text" id="itemName" {...register(`item.${i}.name`, { required: "Can't be empty" })} />
<Error>{errors?.['item']?.[i]?.['name']?.['message']}</Error>
</div>
<div tw="flex flex-col row-start-2 col-start-1 tablet:w-12">
**<label htmlFor="itemsQuantity" tw="text-secondary">Qty.</label>
<StyledInput type="text" id="itemsQuantity" {...register(`item.${i}.quantity`, { valueAsNumber: true }, { required: "Can't be empty" })} />**
<Error>{errors?.['item']?.[i]?.['quantity']?.['message']}</Error>
</div>
<div tw="flex flex-col row-start-2 col-start-2 tablet:w-20">
**<label htmlFor="itemPrice" tw="text-secondary">Price</label>
<StyledInput type="text" id="itemPrice" {...register(`item.${i}.price`, { valueAsNumber: true }, { required: "Can't be empty" })} />**
<Error>{errors?.['item']?.[i]?.['price']?.['message']}</Error>
</div>
<div tw="flex flex-col row-start-2 col-start-3 tablet:w-20">
<label htmlFor="itemPrice" tw="text-secondary">Total</label>
<StyledField>{Intl.NumberFormat('en-GB', { style: "currency", currency: 'GBP' }).format(`item.${i}.price` * `item.${i}.quantity`)}</StyledField>
</div>
<div onClick={() => remove(i)} tw="flex flex-col pt-4 row-start-2 col-start-4 tablet:w-auto place-content-center cursor-pointer">
<Image src="/assets/icon-delete.svg" width={12} height={16} alt="recyclingBin" />
</div>
</div>)}
我想弄清楚的是如何从粗体部分(数量和价格)中提取值,这样我就可以得到他们的产品并将其放在下一个div中。
<StyledField>{Intl.NumberFormat('en-GB', { style: "currency", currency: 'GBP' }).format(**`item[i].price` * `item[i].quantity`**)}</StyledField>
粗体部分是我解决问题的尝试。编译器抛出一个错误,说“项未定义”
任何帮助将不胜感激。谢谢
2条答案
按热度按时间piok6c0g1#
明白了。
我必须使用getValue()来提取我需要的值。
ffx8fchx2#
除了使用getValues()之外,还可以使用从useForm()函数https://www.react-hook-form.com/api/useform/watch/获取的watch函数
1.定义字段数组
的监视常量
1.使用动态字段
中的watch值