onClick未传播

时间:2019-03-09 18:13:19

标签: html reactjs

我在创建一个允许打印图片的简单画廊时遇到了麻烦。我构造了界面。单击打印按钮时,无法将事件传播到函数。有趣的是,它总是只适用于库中的几个项目,因此控制台日志为foo。您能指出问题出在哪里吗?我正在使用material-ui,tileData是带有图片网址等的json ...

非常感谢!

class Galery extends React.Component {
  state = {
    tileData: tileData
  };
  printThis = tile => {
    console.log("printing tile... " + tile.target.value);
  };

  render() {
    const classes = this.props;
    return (
      <div className={classes.root}>
        <ButtonAppBar />
        <div style={{ marginBottom: 20 }} />

        <Grid container spacing={8}>
          <Grid item xs={10}>
            <GridList
              cellHeight={250}
              cellWidth={250}
              cols={5}
              spacing={4}
              className={classes.gridList}
            >
              {tileData.map(tile => (
                <GridListTile key={tile.img}>
                  <img src={tile.img} alt={tile.title} />

                  <GridListTileBar
                    title={tile.title}
                    subtitle={<span>by: {tile.author}</span>}
                    actionIcon={
                      <IconButton
                        className={classes.icon}
                        value="foo"
                        onClick={this.printThis}
                      >
                        <i className="material-icons md-24 md-light">print</i>
                      </IconButton>
                    }
                    secondActionIcon={
                      <IconButton className={classes.icon}>
                        <i className="material-icons md-24 md-light">delete</i>
                      </IconButton>
                    }
                  />
                </GridListTile>
              ))}
            </GridList>
          </Grid>
          <Grid item xs={2}>
            <div className={classes.stats}>
              <StatsTable />
            </div>
          </Grid>
        </Grid>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

根据github的回答https://github.com/mui-org/material-ui/issues/7974#issuecomment-329250974,它可以通过event.currentTarget访问对象ID

所以我的实现是:

printThis = (event) => {
    console.log('printing tile... '+ event.currentTarget.id);
};

<IconButton className={classes.icon} id = {tile.img} onClick={this.printThis}>
                                <i className="material-icons md-24 md-light"  >
                                    print
                                    </i>
                            </IconButton>