Pass variable to onClick in React

时间:2017-11-08 22:03:02

标签: javascript reactjs onclick

I am developing my UI using React and (for now at least) using Material-UI, which has and tags. Inside ListItem, I want to detect a click on an icon. The issue is my list will have a number of listitems, and I want to pass the index of the listite into my click handler. But I also need to pass in the click event itself. My code looks like this:

class SomeList extends React.Component { 

    handleClickDeleteIcon(e) {
        e.stopPropagation();
        console.log('Fired handleClickDeleteIcon()!');
    }

    everywhereClickFunction(e) {
        console.log('Fired everywhereClickFunction()!');
    }

    render() {
        return (
            <List>
              <Subheader inset={true}>Some Files</Subheader>
              <ListItem
                leftAvatar={<Avatar icon={<ActionAssignment />} backgroundColor={blue500} />}
                rightIcon={
                    <div onClick={this.handleClickDeleteIcon}>
                        <DeleteForever />
                    </div>
                }
                primaryText="Vacation itinerary"
                secondaryText="Jan 20, 2014"
                onTouchTap={this.everywhereClickFunction}
                onClick={this.everywhereClickFunction}
              />
              <ListItem
                leftAvatar={<Avatar icon={<ActionAssignment />} backgroundColor={blue500} />}
                rightIcon={
                    <div onClick={this.handleClickDeleteIcon}>
                        <DeleteForever />
                    </div>
                }
                primaryText="Kitchen remodel"
                secondaryText="Jan 10, 2014"
              />
              <ListItem
                leftAvatar={<Avatar icon={<ActionAssignment />} backgroundColor={blue500} />}
                rightIcon={
                    <div onClick={this.handleClickDeleteIcon}>
                        <DeleteForever />
                    </div>
                }
                primaryText="Something else"
                secondaryText="Nov 08, 2017"
              />
            </List>
        );
    }
);

So how can I use onClick for each rightIcon to pass in a variable (like a list index or some unique id) that I can use inside handleClickDeleteIcon(e)? Note that I need handleClickDeleteIcon to also get the event e so I cant call e.stopPropagation().

1 个答案:

答案 0 :(得分:3)

You can create an anonymous function and call your function with params, like this:

<div onClick={e => this.handleClickDeleteIcon(e, index)}>
  <DeleteForever />
</div>