reactjs - 如何根据另一个数字输入中的数字动态创建多个字段?
问题描述
我想要这种行为,下面是代码片段:
当字段 X 更改其数字(整数)值时(通过用户交互):
如果现在 X 的值更大,则将新字段添加到字段数组(称为 A)直到有 X 个字段(数组中的字段应该是
number
-typed 或<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 依赖的情况下实现这种想要的行为。
请帮我!谢谢!
解决方案
我在同一个包 react-hook-form 中使用了 Controller 组件。
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>
);
}}
/>
)
);
}
推荐阅读
- java - SwipeGestureDetector 将图像从 int [] 更改为 Imageview(顶部和底部)
- cocoa - 如何在 Apple Cocoa 应用程序中获取设备 ID?
- cuda - CUDA:为什么将共享内存阵列填充一列会使内核速度降低 250%?
- devexpress - DevExtreme DataGrid 颜色框
- c++ - 加解密生成器项目
- node.js - 为什么使用archiver.file模块压缩文件时出现“队列关闭错误”
- c++ - 在编译期间是否有任何用于替换函数的钩子接口?
- istio - Istio 流量路由通过匹配前缀拒绝
- amazon-web-services - AWS:配置 Cognito 用户以代入特定 IAM 角色以执行 Lambda 函数
- android-studio - Google Play 不接受由另一台 PC 签名的 android app bundle