typescript laravel inertia如何推断inertiaFormProps的类型?

hm2xizp9  于 2023-06-24  发布在  TypeScript
关注(0)|答案(2)|浏览(131)

我有一个使用useForm钩子的页面,这个页面是一个多步骤的表单,被分离成自己的组件。
就像这样:

export default function create(){
    
      const form = useForm({
        name: '',
        content: '',
        is_published: 0,
        some_more_fields_here
      });
    
    
    return (
    <div>
    <GeneralPageInformation form={form} />
    
    
    <SeoInformation form={form} />
    </div>
    )
}

useForm返回的form对象看起来像这样:

InertiaFormProps<{name: string, content: string, is_published: number, rest of your fields}>

我试着做这样的事

interface IGeneralPageInformation {
  form: InertiaFormProps;
}

虽然这确实给予我可以访问form.processtingform.recentlySuccessful之类的东西
当尝试使用form.setData('all available keys should show up here))之类的东西时,namecontent之类的键不可见
我可以像这样手动声明密钥

interface IGeneralPageInformation {
  form:  InertiaFormProps<{name: string, content: string, is_published: number, resf of the fields}>
}

但这显然不是一个非常“可扩展”的解决方案,因为每当表单发生更改时,我都必须手动编辑每个表单。

vq8itlhq

vq8itlhq1#

在Vue 3中,

<script setup lang="ts">
import { InertiaForm, useForm } from "@inertiajs/inertia-vue3"

const form: InertiaForm<{
                title: string,
                category: string,
                types: Array<string | number>
            }> = useForm({
                title: "",
                category: "",
                types: [],
            })
</script>
tpgth1q7

tpgth1q72#

如果你正在使用React,你可以这样做:

import { InertiaFormProps } from '@inertiajs/react/types/useForm'
import { useForm } from '@inertiajs/react'

interface FormInterface {
  email: string
  password: string
}

const MyReactForm = () => {
  // Pass in your type as a generic like below 👇
  const { data, setData }: InertiaFormProps<FormInterface> = useForm({
    email: '',
    password: '',
  })

  return (
    <form>
      <input
        id='email'
        type='email'
        onChange={(e) => setData('email', e.target.value)}
        value={data.email}
      />
      <input
        id='password'
        type='password'
        onChange={(e) => setData('password', e.target.value)}
        value={data.password}
      />
    </form>
  )
}

export default MyReactForm

相关问题