Передача сопоставленных данных в модальный интерфейс материалов - PullRequest
0 голосов
/ 15 февраля 2019

Я пытаюсь передать список значений кнопкам.При нажатии на кнопки должен появиться модал с определенным отображенным значением, но в моем случае только последнее значение (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>
    ))}
  }

проверить по этому коду песочница

1 Ответ

0 голосов
/ 15 февраля 2019

Вы создаете три разных модала в вашей функции 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

...