React On循环打开模态

时间:2018-04-29 14:34:41

标签: javascript reactjs

嗨,我正在学习reactjs,现在我在循环中遇到了Modal的困难。

我的问题是,我的模态没有显示。

这是我目前的代码:

state = {
    modal: false,
    modal_backdrop: false,
    modal_nested_parent: false,
    modal_nested: false,
    backdrop: true,
};

toggle = modalType => () => {
    if (!modalType) {
        console.log(this.state.modal);
        return this.setState({
            modal: !this.state.modal,
        });
    }

    this.setState({
        [`modal_${modalType}`]: !this.state[`modal_${modalType}`],
    });
};

render() {
    let bookItems = [];
    let modalItems = [];
    for (var i = 1; i < 17; i++) {
        bookItems.push(<Col lg="3" md="6" sm="6" xs="12" className="mb-3">
            <a href="#" onClick={this.toggle()}>
                <Card inverse color="dark">
                    <CardBody>
                        <CardTitle className="text-capitalize">
                            <center>{i}</center>
                        </CardTitle>
                    </CardBody>
                </Card>
            </a>
        </Col>);

        modalItems.push(<Modal
            isOpen={this.state.modal}
            toggle={this.toggle()}
            className={this.props.className}
        >
            <ModalHeader toggle={this.toggle()}>{i}</ModalHeader>
            <ModalBody>
                Lorem ipsum dolor sit amet.
            </ModalBody>
            <ModalFooter>
                <Button color="primary" onClick={this.toggle()}>
                    Do Something
                </Button>{' '}
                <Button color="secondary" onClick={this.toggle()}>
                    Cancel
                </Button>
            </ModalFooter>
        </Modal>);
    }

如何显示具有特定ID的模态?因为我的模态目前无效。

我正在使用此https://github.com/reduction-admin/react-reduction模板。

任何帮助都会表示赞赏。

Editted

这是我目前的退货代码:

 return (
        <Page title="Modals" breadcrumbs={[{ name: 'modals', active: true }]}>
            <Row>
                <Col md="12" sm="12" xs="12">
                    <Card>
                        <CardHeader>Modal</CardHeader>
                        <CardBody>
                            <Row>
                                {bookItems}
                            </Row>
                                {modalItems}
                        </CardBody>
                    </Card>
                </Col>
            </Row>
        </Page>
    );

1 个答案:

答案 0 :(得分:1)

看起来您没有显示渲染函数返回的内容。它会返回模态数组吗?

要显示具有当前id的模态,请在循环内首次创建组件时传入id:

this.toggle(id, modalType)

将功能签名更改为

toggle = (id, modalType) = () => {
  this.setState({
  currentId: id,
  [modalType]: !this.state[modalType],
}

这将创建一个新的闭包函数,该函数在每个按钮内存储id和modalType,单击时将触发正确的setState。然后,您可以使用模态中存储状态的currentId。

相关问题