将映射的数据传递到Material-UI模式

时间:2019-02-15 06:44:01

标签: reactjs material-ui

我正在尝试将值列表传递给按钮。单击按钮后,将出现具有特定映射值的模态,但在我的情况下,所有模态中仅出现数组中的最后一个值(3) ... 我该如何解决?

  state = {
    open: false,
    stationData : [
      { id:1, number:'1' },
      { id:2, number:'2' },
      { id:3, number:'3' }
    ],
  };

  handleOpen = () => {
    this.setState({ open: true });
  };

  handleClose = () => {
    this.setState({ open: false });
  };

  render() {
    const {stationData} = this.state;
    {stationData.map((station,index) => (
        <div key={index}>
            <Button variant="contained" color="primary" style={styles.button} onClick={this.handleOpen}>
                {station.number}
            </Button>
            <Modal 
                open={this.state.open} 
                onClose={this.handleClose} 
                aria-labelledby={index} 
                aria-describedby={index}
            >
                <div style={styles.modal}>
                    {station.number}
                </div>
            </Modal>
        </div>
    ))}
  }

查看此代码sandbox

1 个答案:

答案 0 :(得分:0)

您正在stationData.map()函数中创建三个不同的模态,并且每个模态都依赖于一个状态this.state.open。因此,每当按下一个按钮时,所有三个按钮都将打开,并且您会看到最后一个位于顶部。所以3总是可见的。

您应该做的是-仅创建一个模式并跟踪在新状态this.state.stationNumber中按下了哪个按钮。这样,将触发唯一的模态,并且它将知道从状态渲染什么。

这是您修改的代码,我在必要时添加了注释:

class Dashboard extends React.Component {
  state = {
    open: false,
    stationNumber: null,
    stationData: [
      { id: 1, number: "1" },
      { id: 2, number: "2" },
      { id: 3, number: "3" }
    ]
  };

  handleOpen = stationNumber => () => {
    // get which button was pressed via `stationNumber`
    // open the modal and set the `stationNumber` state to that argument
    this.setState({ open: true, stationNumber: stationNumber });
  };

  handleClose = () => {
    this.setState({ open: false });
  };
  render() {
    const { stationData } = this.state;

    return (
      <div style={styles.wrapper}>
        <div style={styles.body}>
          <Paper square elevation={0} style={styles.container}>
            {stationData.map((station, index) => (
              <div key={index}>
                <Button
                  variant="contained"
                  color="primary"
                  style={styles.button}
                  // pass which button was clicked as an argument
                  onClick={this.handleOpen(station.number)}
                >
                  {station.number}
                </Button>
              </div>
            ))}
          </Paper>

          {/* add only one modal */}
          <Modal open={this.state.open} onClose={this.handleClose}>
            {/* display the content based on newly set state */}
            <div style={styles.modal}>{this.state.stationNumber}</div>
          </Modal>
        </div>
      </div>
    );
  }
}

Edit Material UI Playground