如何将数组索引值从数组映射传递到React中的onClick函数?



如何将book.id值从数组映射传递到onClick函数?

import { bookData } from './data';
const App = () => {
const [state, setState] = useState(bookData)
const handleDelete = (bookId) => {
return (
console.log(bookId)
)
};
return
<div className='bookCards'>
{state.map((book) => {
return (
<div className='bookCard' key={book.id}>
<img className='coverImg' src={ book.coverimg } ></img>
<div>Title: { book.title }</div>
<div>Author: { book.author }</div>
<div>Year: { book.year_written }</div>
<div>Edition: { book.edition }</div>
<button onClick={handleDelete({ book.id })}>delete</button>                        
</div>
)
})}
</div>
export default App;

您需要调用它并将id传递给它,如下所示:

<button onClick={e => handleDelete(book.id)}>delete</button>

相关文档:向事件处理程序传递参数

如果您想看到传入的id打印在控制台上,还可以将handleDelete的主体更改为console.log(bookId)

const handleDelete = (bookId) => {
console.log(bookId)        
};

相关内容

  • 没有找到相关文章

最新更新