0

当我点击记录时,我想显示更多详细信息的模式窗口。我正在使用 OfficeUI。

我的父组件:

public render() {
    {
        return (
            <div>
                {this.props.items
                    .map((item: IListItem, i: number): JSX.Element => <ul className="list-group">
                        <li className="list-group-item">
                            <div className={styles.text}>
                                <p>{item.Id}</p>
                            </div>
                            <DefaultButton onClick={this.showModalEvent} text="Open Modal" />
                            {this.state.showPopup
                                ? <ModalPopUpItem item={item} 
                                        showModalState={this.state.showPopup}
                                        showModal={this.showModalEvent}/> : null
                            }
                        </li>
                    </ul>)}
            </div>
        );
    }



    private showModalEvent = (): void => {
    this.setState({ showPopup: !this.state.showPopup });
}

我的孩子:

export class ModalPopUpItem extends React.Component<IModalProps> {
    public render() {
        return (
            <Modal
                isOpen={this.props.showModalState}
                onDismiss={this.props.showModal}
                isBlocking={false}
                containerClassName="ms-modalExample-container">
                <div className="ms-modalExample-header">
                    <span>{this.props.item.date}</span>
                </div>
            </Modal>
        );
    }
}

当我在父组件上单击我的DeafultButton时,它会为每个项目调用并显示Modal,我如何将其限制为仅一个当前单击的项目。我试过i: number,但我想不通。

4

2 回答 2

0

您的父组件只有一个标志来存储showPopup. 这意味着当您单击其中一个按钮时,您会为整个父组件设置此标志,这意味着您的子组件的整个列表this.state.showPopup都会被评估并且将为真。

您需要找到一种方法来将单击按钮的效果限制为单击该按钮的项目。

例如,您可以不在showPopup父组件上设置标志,而是在item.

这可能有效,但您必须重新审视包含ModalPopUpItem.

private showModalEvent = (item): void => {
    item.showPopup = !item.showPopup;
}
于 2018-10-01T09:28:27.367 回答
0

由于您为每个孩子使用单一状态,因此一旦您更改this.state.showPopup为 true,每个模式都会出现。所以你可以改变showModalEvent方法。

private showModalEvent = (id: number): void => {
    this.setState({ showPopupId: id });

渲染看起来像

return (
  <div>
    {this.props.items
      .map((item: IListItem, i: number): JSX.Element => <ul className="list-group">
        <li className="list-group-item">
          <div className={styles.text}>
            <p>{item.Id}</p>
          </div>
          <DefaultButton onClick={() => this.showModalEvent(item.Id)} text="Open Modal" />
          {this.state.showPopupId === item.Id
            ? <ModalPopUpItem item={item}
              showModalState={this.state.showPopup}
              showModal={this.showModalEvent} /> : null
          }
        </li>
      </ul>)}
  </div>
);

由于此方法一次只存储一个 id,这意味着只会显示一个模式。如果您当时想显示更多模态,可以将其更改为数组或其他内容。

于 2018-10-01T09:33:01.960 回答