我正在开发我的第一个 MERN 堆栈项目,这是一个图书馆管理系统,我一直在对大多数 UI 元素使用模态。下面是我的 BookRow 模式的代码(它在表格中呈现一本书行,单击时打开一个模式)
import React from "react";
//import components
import DeleteBook from "./DeleteBook";
import EditBook from "./EditBook";
const BookRow = ({ book }) => {
return (
<>
<tr
className="cursor-pointer hover:bg-gray-200 border border-gray-300"
onClick={() => document.getElementById(`book_modal_${book._id}`).showModal()}
>
<td className="border border-gray-300">{book.title}</td>
<td className="border border-gray-300">{book.author}</td>
</tr>
<dialog id={`book_modal_${book._id}`} className="modal">
<div className="modal-box">
<h3 className="font-bold text-lg">{book.title}</h3>
<p className="">Author: {book.author}</p>
<p className="">Category: {book.category}</p>
<p className="">ISBN: {book.isbn}</p>
<p className="">Reference ID: {book.refId}</p>
<div className="modal-action flex justify-end gap-2 mt-4">
<DeleteBook book={book} />
<EditBook book={book} />
<button
className="btn"
onClick={() => document.getElementById(`book_modal_${book._id}`).close()}
>
Close
</button>
</div>
</div>
</dialog>
</>
);
};
export default BookRow;
问题在于,传递的 prop 不是模态打开的书,而是状态中的第一本书。我可能做错了什么?
我尝试询问chatGPT,但没有得到任何正确的答复
你的整个做法都是错误的
你应该有一个状态
你应该有状态
import React from "react";
//import components
import DeleteBook from "./DeleteBook";
import EditBook from "./EditBook";
const BookRow = ({ book }) => {
// add state here !!!
const [showModal, setShowModal] = useState(false)
return (
<>
<tr
className="cursor-pointer hover:bg-gray-200 border border-gray-300"
onClick={() => setShowModal(true)
>
<td className="border border-gray-300">{book.title}</td>
<td className="border border-gray-300">{book.author}</td>
</tr>
{ setShowModal &&
<dialog id={`book_modal_${book._id}`} className="modal">
<div className="modal-box">
<h3 className="font-bold text-lg">{book.title}</h3>
<p className="">Author: {book.author}</p>
<p className="">Category: {book.category}</p>
<p className="">ISBN: {book.isbn}</p>
<p className="">Reference ID: {book.refId}</p>
<div className="modal-action flex justify-end gap-2 mt-4">
<DeleteBook book={book} />
<EditBook book={book} />
<button
className="btn"
onClick={() => setShowModal(false)
>
Close
</button>
</div>
</div>
</dialog>
}
</>
);
};
export default BookRow;