
修改handlesubmit函数
接下来,修改handleSubmit函数,使其接收event对象和item对象作为参数。在函数内部,从item对象中获取id,并将其添加到payload中。
const handleSubmit = (e, item) => {
e.preventDefault();
const payload = {
jobId: item.id, // 将jobId添加到payload
comment: textareaValue,
user: currentUser.id,
};
console.log(payload);
// 在此处添加发送payload到后端的代码
// 例如:
// fetch('/api/comments', {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json',
// },
// body: JSON.stringify(payload),
// })
// .then(response => response.json())
// .then(data => {
// console.log('Success:', data);
// })
// .catch((error) => {
// console.error('Error:', error);
// });
};完整代码示例
以下是包含上述修改的完整代码示例:
import React, { useState } from 'react';
import { Form, InputGroup, Image } from 'react-bootstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPaperPlane } from '@fortawesome/free-solid-svg-icons';
const CommentForm = ({ item, currentUser, asset, time }) => {
const [textareaValue, setTextareaValue] = useState('');
const handleTextareaChange = (e) => {
setTextareaValue(e.target.value);
};
const handleSubmit = (e, item) => {
e.preventDefault();
const payload = {
jobId: item.id, // 将jobId添加到payload
comment: textareaValue,
user: currentUser.id,
};
console.log(payload);
// 在此处添加发送payload到后端的代码
// 例如:
// fetch('/api/comments', {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json',
// },
// body: JSON.stringify(payload),
// })
// .then(response => response.json())
// .then(data => {
// console.log('Success:', data);
// })
// .catch((error) => {
// console.error('Error:', error);
// });
// 清空textarea
setTextareaValue('');
};
return (
<Form onSubmit={(e) => handleSubmit(e, item)} type="submit">
<InputGroup className="mb-3 comment-sect">
<InputGroup.Text id="inputGroup-sizing-default">
<Image src={asset('small', currentUser.profil_picture)} rounded className="profil-comment" />
</InputGroup.Text>
<Form.Control
as="textarea"
rows={1}
value={textareaValue}
onChange={handleTextareaChange}
aria-label="Default"
aria-describedby="inputGroup-sizing-default"
/>
<div
className={`comment-send-container ${textareaValue.trim() !== '' ? 'active-icon' : 'disable-icon'}`}
onClick={(e) => handleSubmit(e, item)} // 确保点击事件也传递 item
>
<FontAwesomeIcon icon={faPaperPlane} className="comment-send-icon" />
</div>
</InputGroup>
</Form>
);
};
export default CommentForm;注意事项
总结
通过以上步骤,我们成功地将job ID从循环传递到payload中,从而实现了评论与特定job的关联。这种方法可以应用于各种需要将循环数据传递到事件处理函数中的场景。记住要根据你的具体需求调整代码,并确保在生产环境中进行充分的测试。
以上就是如何在循环中将job.id传递到payload以存储评论的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号