Remix 使用提交任意数据

Edo*_*don 4 javascript reactjs remix.run

我正在尝试使用 Remix 的 useSubmit 挂钩提交表单。但我希望能够随表单提交数据一起传递任意数据。

我有一些带有禁用/只读属性的静态值的表单元素,这意味着在表单提交时它们的值将为空。不过,我可以在变量中访问它们的实际值post,我想将其发送到我的操作。

export const action: ActionFunction = async (request) => {
  // I want access to {arbitraryData} here passed from submit
}

export default function EditSlug() {
  const post = useLoaderData();

  // ...Submit handler passing arbitrary data (post.title in this case)
  const handleSubmit = (event: any) => {
      submit(
        { target: event?.currentTarget, arbitraryData: post.title },
        { method: "post", action: "/admin/edit/{dynamicRouteHere}" }
      );
    };

  return(
  <Form method="post" onSubmit={handleSubmit}>
            <p>
              <label>
                Post Title:
                <input
                  type="text"
                  name="title"
                  value={post.title}
                  disabled
                  readOnly
                />
              </label>
            </p>
Run Code Online (Sandbox Code Playgroud)

有没有办法使用handleSubmit 在我的操作中接收自定义数据?

小智 7

另一种方法是

export const action: ActionFunction = async (request) => {
  // I want access to {arbitraryData} here passed from submit
  // Now u can get this in formData.
}

export default function EditSlug() {
  const post = useLoaderData();
  const formRef = useRef<HtmlFormElement>(null); //Add a form ref.
  // ...Submit handler passing arbitrary data (post.title in this case)
  const handleSubmit = (event: any) => {

      const formData = new FormData(formRef.current)
      formData.set("arbitraryData", post.title)
      
      submit(
        formData, //Notice this change
        { method: "post", action: "/admin/edit/{dynamicRouteHere}" }
      );
    };

  return(
  <Form ref={formRef} method="post" onSubmit={handleSubmit}>
            <p>
              <label>
                Post Title:
                <input
                  type="text"
                  name="title"
                  value={post.title}
                  disabled
                  readOnly
                />
              </label>
            </p>
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您将更改原始 formData 并向其添加另一个键并使用它来提交表单。