How can I send object to the onClick event in react? I have a list of items where every item is related to the object in state object. It is created in method getList() in the component:
import React from 'react';
import ReactDOM from 'react-dom';
function ItemsList() {
/*constructor(props)
{
//super(props);
//this.state.list = [1,2,3,4,5,6,7,8,9];
}*/
let state = {
list: [
{id:1, name: 'aaa'}, {id: 2, name: 'bbb'}, {id: 3, name: 'ccc'}
]
}
return (
<div>
{getList()}
</div>
)
function getList()
{
let items = state.list.map(item => { return (<li key={item.id} onClick={handleClick} className={item.id > 5 ? 'green' : 'red'}>item: {item.name}</li>) });
return <ul>{items}</ul>
}
function handleClick(event) { // Here I want to get item + event object as params
alert(event);
}
}
export default ItemsList;
if (document.getElementById('itemsList')) {
ReactDOM.render(<ItemsList />, document.getElementById('itemsList'));
}
How can I send item object to onClick event?
Oh as I wrote the question I tried call anonymouse function from onclick and it works
onClick={e => {handleClick(item, e)}}
just adding one more way:-
const myCustomOnClick = (e: Event || EventArgsType): clickType => handleClick(item,e)
onClick={this.myCustomOnClick}
-- class component
onClick={myCustomOnClick}
-- functional or hooks or composable component
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.