使用唯一的注册{}名称和ID动态创建Reach Hook表单输入。

huangapple go评论75阅读模式
英文:

Reach hook form create inputs dynamically with unic register{} name and id

问题

我正在动态创建数组内的新输入,并且每个输入都会有自己的 idregister{} 名称。为了做到这一点,我使用 array.map() 中的 index 值。

registerTrip() 函数中,我试图将每个输入值添加到一个数组中,将 counter 数字连接到 data.trip_start_date,以便能够从输入中获取相应的值,但这个过程没有起作用。

即使我将变量 i 转换为字符串,我也无法将它们连接起来。

如果我 console.log(data.trip_start_date0),我可以获得值,但是当我 console.log(data.trip_start_date + s) 时,我会得到 undefined0undefined1...

这样做是正确的方式吗,还是我应该以不同的方式来做呢?

英文:

I'm creating new inputs dynamically inside an array and each input will have its own id and register{} name. To do that, I'm using index value from array.map().

In registerTrip() function I'm trying to add each input value to an array concatenating counter number to data.trip_start_date to be able to get the corresponding value from the input but this process is not working.

I'm not able to concatenate them even if I convert var i to string.

If I console.log(data.trip_start_date0) I can get the value but when I console.log(data.trip_start_date + s) I get undefined0, undefined1...

Is this the correct way to do that or I should do it differently?


export function RegisterTrips() {

const { register, handleSubmit, formState: { errors }, reset } = useForm();
const [counter, setCounter] = useState(1);


const createDate = () => {
   setCounter(counter + 1);
   console.log(counter);
};

const registerTrip = (data: any) => {

    const formData = new FormData();

    let i;
    let s;
    let trip_start_date;
    const dates = [];
    for (i = 0; i < counter; i++) {

        console.log(i);
        console.log(data.trip_start_date0);
        console.log(typeof (data.trip_start_date0));

        s = i.toString();
        trip_start_date = data.trip_start_date + s;
        // dates.push("trip_start_date", data.trip_start_date.${ i });

        console.log(data.trip_start_date0);
        console.log(trip_start_date);
        // console.log(dates);
     }

}

return(

...

{
    Array.from(Array(counter)).map((e, index) => {
        return (
          <div className = "flex flex-col gap-2 lg:flex-row w-full">

            <div className = "w-full">
          
            	<label htmlFor = {`trip_start_date${index}` className = "block mb-2 text-sm text-slate-500"> Trip Date </label>
					
				<input
					type = "date"
            		className = "w-full px-2 py-2 text-sm text-slate-600 border border-slate-300 focus:border-slate-400 focus:outline-none rounded-lg"
            		id = {`trip_start_date${index}`}
					{...register(`trip_start_date${index}`, {required: false})}
            	/>
            </div>
        )
    })
}

<div className="flex justify-end mt-4 w-full">
   <button type='button' className="text-sm text-blue-500 underline cursor-pointer underline-offset-4 active:text-blue-400" onClick={createDate}>Add new date +</button>
</div>

...

)
}

答案1

得分: 1

当你执行 data.trip_start_date + s 时,你试图访问 data.trip_start_date(该值不存在),然后将其与 s 连接起来。而你想要做的是访问 trip_start_date0(以及1、2、3等)的值。

trip_start_date = data["trip_start_date" + i.toString()];

然而,对于值数组,你应该使用 https://react-hook-form.com/docs/usefieldarray 进行操作。

英文:

When you do data.trip_start_date + s you are trying to access the value of data.trip_start_date (which does not exist) and then concatenate that with s. Whereas what you want to do is access the value of trip_start_date0 (and 1,2,3 etc).

trip_start_date = data["trip_start_date" + i.toString()];

However, you should be aware for arrays of values you are supposed to use https://react-hook-form.com/docs/usefieldarray.

huangapple
  • 本文由 发表于 2023年6月2日 04:15:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76385411.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定