如何根据另一个数字输入中的数字动态创建多个字段?
How to dynamically create a number of fields based on the number in another number input?
我想要这种行为,下面是代码片段:
当字段 X 更改其数字(整数)值(通过用户交互)时:
如果 X 的值现在更大,向字段数组(称为 A)添加新字段,直到有 X 个字段(数组中的字段应该是 number
类型或<select>
s)
否则如果 X 的值现在更低,则删除字段数组 A 中的最后一个字段,直到只有 X 个字段
这是我的起点:
const { fields, append, prepend, remove, swap, move, insert } = useFieldArray(
{
control,
name: "A",
}
);
watch((data, options) => {
// console.log('d, o', data, options);
if (options.name === 'X') {
let z = data.X;
while (z) {
// remove?
--z;
}
}
});
在文档中,据说不会在单个渲染中放置多个删除调用,如果输入不以影响现有值的方式更改其值(因此值在A应该保留)。
我也用这个,但它是组件的另一部分,应该没问题:
{X > 0 && (
<div>
{fields.map((field, index) => {
...
我可以在纯 React 中执行此操作,但我正在使用 react-hook-form 模块,我正在徘徊如何在不放弃 react-hook-form 依赖项的情况下执行此所需的行为。
请帮帮我!谢谢!
我在同一个包中使用了the Controller component,react-hook-form。
if (f.type === "multiple") {
return (
f.condition() && (
<Controller
control={control}
name={f.name}
defaultValue={[]}
render={({
field: { onChange, onBlur, value, name, ref },
fieldState: { invalid, isTouched, isDirty, error },
formState,
}) => {
let seq = [];
const x = f.count();
for (let i = 0; i < x; i++) {
seq.push(i);
}
return (
<div tabIndex={0} onBlur={onBlur} ref={ref}>
{seq.map((field, index) => {
return (
<React.Fragment key={index}>
{f.renderChild({ index, onChange })}
</React.Fragment>
);
})}
</div>
);
}}
/>
)
);
}
我想要这种行为,下面是代码片段:
当字段 X 更改其数字(整数)值(通过用户交互)时:
如果 X 的值现在更大,向字段数组(称为 A)添加新字段,直到有 X 个字段(数组中的字段应该是
number
类型或<select>
s)否则如果 X 的值现在更低,则删除字段数组 A 中的最后一个字段,直到只有 X 个字段
这是我的起点:
const { fields, append, prepend, remove, swap, move, insert } = useFieldArray(
{
control,
name: "A",
}
);
watch((data, options) => {
// console.log('d, o', data, options);
if (options.name === 'X') {
let z = data.X;
while (z) {
// remove?
--z;
}
}
});
在文档中,据说不会在单个渲染中放置多个删除调用,如果输入不以影响现有值的方式更改其值(因此值在A应该保留)。
我也用这个,但它是组件的另一部分,应该没问题:
{X > 0 && (
<div>
{fields.map((field, index) => {
...
我可以在纯 React 中执行此操作,但我正在使用 react-hook-form 模块,我正在徘徊如何在不放弃 react-hook-form 依赖项的情况下执行此所需的行为。
请帮帮我!谢谢!
我在同一个包中使用了the Controller component,react-hook-form。
if (f.type === "multiple") {
return (
f.condition() && (
<Controller
control={control}
name={f.name}
defaultValue={[]}
render={({
field: { onChange, onBlur, value, name, ref },
fieldState: { invalid, isTouched, isDirty, error },
formState,
}) => {
let seq = [];
const x = f.count();
for (let i = 0; i < x; i++) {
seq.push(i);
}
return (
<div tabIndex={0} onBlur={onBlur} ref={ref}>
{seq.map((field, index) => {
return (
<React.Fragment key={index}>
{f.renderChild({ index, onChange })}
</React.Fragment>
);
})}
</div>
);
}}
/>
)
);
}