数组元素上的ReactJS onClick事件

时间:2019-06-14 15:31:04

标签: arrays reactjs onclick

我需要在图像网格中选择图像。目前,我一次只能选择一张图像。选择一个时,另一个取消选择。我想选择每个想要的图像(一次选择许多图像)。我无法通过onClick事件在每个元素上激活isToggle布尔值。

class Gallery extends Component{
  constructor(props) {
    super(props);
    this.state = {
    //isToggleOn: true,
    selected: '',
    };

    this.handleClick = this.handleClick.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleClick = key => {
    this.setState(state => ({
      //isToggleOn: !state.isToggleOn,
      selected: key,
    }));
    //console.log(this.state)
  } 

  render(){
  //const classes = useStyles();
  return (
    <Container>
    <Row >
    <Col>
    <div style={styles.root}>
      <GridList cellHeight={160} style={styles.gridList} cols={3}>
        {tileData.map((tile,i) => (
          <GridListTile key={i} cols={tile.cols || 1} onClick={() => this.handleClick(tile)} >
            <img src={tile.img} alt={tile.title} style={this.state.selected === tile  ? styles.inputClicked:styles.inputNormal} />
          </GridListTile>
        ))}
      </GridList>
    </div>
    </Col>
    </Row>
    </Container>
  );
}
}


export default Gallery;

I can only select one image at a time. I expect to select many at a time.

1 个答案:

答案 0 :(得分:0)

点击磁贴时,您需要添加到所选磁贴的数组中,如下所示:

handleClick = tile => {
    this.setState({
      selected: this.state.selected.concat([tile]),
    });
  } 

然后在渲染时,您可以检查是否选择了如下所示的图块:

<img src={tile.img} alt={tile.title} style={isSelected(this.state.selected, tile)  ? styles.inputClicked:styles.inputNormal} />

具有:

isSelected = (selected, tile) => {
    // some logic to check that the tile is already selected e.g.
    return selected.find(tileItem => tileItem.title === tile.title)
}

确保在构造函数中将所选状态初始化为[]:

this.state = {
    selected: [],
    };

更新:

如果您也要删除图块,则必须执行以下操作:

handleClick = tile => {
    const { selected } = this.state;
    if(selected.find(item ==> item.title === tile.title)) {
       // need to remove tile
       this.setState({
         selected: selected.filter(item => item.tile !== tile.title),
       });
    } else {
       this.setState({
         selected: this.state.selected.concat([tile]),
       });
    }
  }