【问题标题】:Pass variable to onClick in React [duplicate]在 React 中将变量传递给 onClick [重复]
【发布时间】:2018-04-21 18:35:49
【问题描述】:

我正在使用 React 开发我的 UI,并且(至少现在)使用 Material-UI,它有 和 标签。在 ListItem 内,我想检测对图标的点击。问题是我的列表会有许多列表项,我想将列表项的索引传递给我的点击处理程序。但我还需要传入点击事件本身。我的代码如下所示:

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>
        );
    }
);

那么我如何使用 onClick 为每个 rightIcon 传递一个我可以在 handleClickDeleteIcon(e) 中使用的变量(如列表索引或某些唯一 ID)?请注意,我需要 handleClickDeleteIcon 来获取事件 e,所以我不能调用 e.stopPropagation()。

【问题讨论】:

    标签: javascript reactjs onclick


    【解决方案1】:

    您可以创建一个匿名函数并使用参数调用您的函数,如下所示:

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

    【讨论】:

      猜你喜欢
      • 2010-12-07
      • 1970-01-01
      • 1970-01-01
      • 2016-03-07
      • 1970-01-01
      • 2019-10-18
      • 2014-01-11
      • 2016-02-23
      • 2013-01-28
      相关资源
      最近更新 更多