更改<cardmedia>中的图像

时间:2019-03-14 16:42:12

标签: reactjs material-design material-ui

我有一组图像。我想在用户每次按下图像时更新CardMedia中的图像。

我无法确定的是如何获取数组中的下一个图像(当前索引)?

<Grid item xs>
  <Card className={classes.card}>
    <CardHeader
      avatar={
        <Avatar aria-label="Recipe" className={classes.avatar}>
          R
        </Avatar>
      }
      title="Title ....."
      subheader="September 14, 2016"
    />
    <CardMedia
      id="cm"
      className={classes.media}
      image="https://material-ui-next.com/static/images/cards/contemplative-reptile.jpg"
      title="Title"
      onClick={this.onClick}
    />
  </Card>
</Grid>

onClick() {
  console.log("** onClick **");
  //How to update the backgroundImage with the next image in the Array ???
  document.getElementById("cm").style["backgroundImage"] =
    "url('./wind/saxophones.jpg')";
}

constructor(props) {
  super(props);
  this.state = {
    IMAGES: [
      {
        url: "./wind/baritones.jpg"
      },
      {
        url: "./wind/saxophones.jpg"
      },
      {
        url: "./wind/flute-893911__340.jpg"
      }
    ]
  };
}

谢谢

1 个答案:

答案 0 :(得分:3)

从imageIndex = 0开始:

constructor(props) {
  super(props);
  this.state = {
    imageIndex: 0,
    IMAGES: [{
    ...

在CardMedia中,您需要使用状态引用当前选定的图像:

<CardMedia
  id='cm'
  className={classes.media}
  image={this.state.IMAGES[this.state.imageIndex]}
  title="Title"
  onClick={this.onClick}
/>

然后在您的onClick处理程序中:

onClick() {
  // now set the image
  this.setState({imageIndex: this.state.imageIndex + 1})
}

最后,您可能需要将this绑定到onClick处理程序:

onClick={this.onClick.bind(this)}