如何在QWIK中以编程方式更新自定义表单组件值?

Ho to update custom form component value programmatically in QWIK?

提问人:jhon dano 提问时间:9/6/2023 最后编辑:jhon dano 更新时间:9/10/2023 访问量:96

问:

问题描述:

在组件中,使用 +/- 按钮时,输入元素的显示值会正确更新。但是,在提交表单时,相应的表单字段与默认值相同,并且不反映更新后的值。Counterfield.value

重现步骤:

  1. 在窗体中使用组件。Counter
  2. 为 设置一个首字母(例如,99)。valueCounter
  3. 单击“-”按钮递减值。
  4. 观察输入字段的显示值是否正确更新。
  5. 提交表单。
  6. 检查与组件关联的值。field.valueCounter
  7. 请注意,它与默认值 (99) 相同,不反映更新后的值。field.value

预期成果:

提交表单时,应反映组件的更新值,而不是默认值。field.valueCounter

实际结果:

与组件关联的 在提交表单时保留默认值,即使输入字段中显示的值已正确更新。field.valueCounter

import { $, component$, useSignal } from '@builder.io/qwik';
import {routeLoader$, z } from "@builder.io/qwik-city";
import { useForm, type InitialValues, formAction$, zodForm$ } from "@modular-forms/qwik";
import type { SubmitHandler } from "@modular-forms/qwik";

interface CounterProps {
  name?: string;
  value?: number;
  attributes?: any
}

export const Counter = component$<CounterProps>((props) => {
  const { value = 0, attributes, name } = props;
  const count = useSignal<number>(value);

  const setValue = $((value: number) => {
    count.value = value;
  });

  return (
    <div>
      <button
        type="button"
        onClick$={() => setValue(count.value - 1)}>
        -
      </button>
      <input
        type="number"
        name={name}
        value={count.value}
        {...attributes}
        onChange$={(e) => setValue(parseInt(e.target.value))}
      />
      <button
        type="button"
        onClick$={() => setValue(count.value + 1)}>
        +
      </button>
    </div>
  );
});

const formSchema = z.object({
  availability: z
    .object({
      daily: z.number().optional()
    })
    .optional()
});

type myForm = z.infer<typeof formSchema>;

export const useFormLoader = routeLoader$<InitialValues<myForm>>(() => ({
  availability: {
    daily: undefined
  }
}));

export const useFormAction = formAction$<myForm>(async (form) => {

  console.log('form: ', form);

}, zodForm$(formSchema));

export default component$(() => {

  const [, { Form, Field }] = useForm<myForm>({
    loader: useFormLoader(),
    action: useFormAction(),
    validate: zodForm$(formSchema),

  });

  const handleSubmit = $<SubmitHandler<myForm>>((values) => {
    console.log('handleSubmit.values: ', values);
  });

  return (
    <Form onSubmit$={handleSubmit}>
     {[
          'daily'
        ].map(name =>
          <Field key={availability-${name}-k} name={availability.${name as 'daily'}}>
          {(field, props) => (
            <Counter
                id ={availability-${name}}
                name ={availability.${name}}
                label ={${name} limit}
                value ={field.value}
                attributes ={props}
                error ={field.error}
            />
          )}
        </Field>
        )}
        <button type="submit" >
          SAVE 
        </button>
    </Form>
  );
});

JavaScript qwik qwikjs

评论


答: 暂无答案