gpt4 book ai didi

javascript - 点击时如何从表单中获取数据?

转载 作者:行者123 更新时间:2023-12-02 23:16:04 25 4
gpt4 key购买 nike

我在组件内有表单:

const MyPopup = ({ name, authenticity_token }) => {
<form className="new_review" id="new_review" action="/reviews" acceptCharset="UTF-8" method="post">
<input name="utf8" type="hidden" value="✓" />
<input type='hidden' name='authenticity_token' value={authenticity_token} />
<input value="2" type="hidden" name="review[reviewable_id]" id="review_reviewable_id" />
<Popup
// ...
footer={
<SendButton
onClick={() => {
setMessageShown(true);
}}
/>
}
// ...
>
<div className="input-group input-group_indent-b_default">
<label className="input-group__label" name='review[email]'>email</label>
<input className="input-group__input" name='review[email]' type="email" />
</div>
</form>

您需要将此表单的数据发送到服务器。 Ajax 请求。点击提交时如何获取表单数据?

const SendButton = () => (
<button
onClick={e => {
const data = new FormData(e.target);
}}
className="button popup-footer__button"
>
Отправить
</button>
);

常量数据为空

最佳答案

尝试将提交功能从按钮本身中抽象出来。定义 handleSubmit() 函数并将其与表单的 onSubmit 处理程序配对。让按钮尽可能简单,您仍然可以让它执行任何视觉操作或其他功能,但让表单处理实际的提交功能。

您可以执行以下操作来从表单中提取数据:

工作沙箱:https://codesandbox.io/s/hardcore-austin-bhq8m

我的弹出窗口:

import React from "react";
import Popup from "./Popup";

const handleSubmit = e => {
e.preventDefault();
const data = new FormData(e.target);
const dataIterator = Array.from(data);

const postObject = dataIterator.reduce((obj, [key, value]) => {
return {
...obj,
[key]: value
};
}, {});

console.log(postObject);
};

const MyPopup = ({ name, authenticity_token }) => {
return (
<form
onSubmit={handleSubmit}
className="new_review"
id="new_review"
action="/reviews"
acceptCharset="UTF-8"
method="post"
>
<input name="utf8" type="hidden" value="✓" />
<input
type="hidden"
name="authenticity_token"
value={authenticity_token}
/>
<input
value="2"
type="hidden"
name="review[reviewable_id]"
id="review_reviewable_id"
/>
<div className="input-group input-group_indent-b_default">
<label className="input-group__label" name="review[email]">
email
</label>
<input
className="input-group__input"
name="review[email]"
type="email"
/>
<Popup />
</div>
</form>
);
};

export default MyPopup;

弹出窗口

import React from "react";

const Popup = props => {
return <button type="submit">Submit</button>;
};

export default Popup;

postObject 包含表单中的所有数据,我假设这就是您想要执行的请求:)

关于javascript - 点击时如何从表单中获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57158195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com