重新混合使用提交任意数据

问题描述 投票:0回答:3

我正在尝试使用 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>

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

javascript reactjs remix.run
3个回答
8
投票

另一种方法是

import { useSubmit } from "@remix-run/react";

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 submit = useSubmit();
  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>

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


3
投票

(就其价值而言,只读输入会发送到表单,而禁用则不会,所以也许您只能使用只读)

要将任意数据提交到操作,您可以使用隐藏输入:

 <Form method="post" onSubmit={handleSubmit}>
            <p>
              <label>
                Post Title:
                <input
                  type="text"
                  name="title"
                  value={post.title}
                  disabled
                  readOnly
                />
                <input type="hidden" name="title" value={post.title} />
              </label>
            </p>

1
投票

你应该能够做到

<Form method="post" onFormdata={handleFormdata} onSubmit={handleSubmit}>

formdata 事件侦听器的回调函数在提交表单之前运行,让您有机会添加或修改正在发送的数据。

© www.soinside.com 2019 - 2024. All rights reserved.