轮播 - 如何从选择

时间:2017-08-02 20:50:32

标签: reactjs carousel

我正在使用反应引导程序并且有旋转木马。想要从选择中选择轮播项目和打开模态但是无法做任何帮助

1 个答案:

答案 0 :(得分:0)

我首先将Carousel.Item组件包装起来,然后为包装的实例添加一个模态和单击处理程序,如下所示

class Item extends Component {
    constructor() {
        super();

        this.state = {
            show: false
        };
    }

    render() {
        const { caption, title, src, alt, className, modal } = this.props;

        return (
            <Carousel.Item>
                <img
                    className={className}
                    src={src}
                    alt={alt}
                    onClick={e => this.setState({ show: true })}
                />
                <Carousel.Caption>
                    <h1>
                        {title}
                    </h1>
                    <p>
                        {caption}
                    </p>
                </Carousel.Caption>

                {/* --> modal instance <-- */}
                <Modal
                    show={this.state.show}
                    onHide={() => this.setState({ show: false })}
                >
                    <Modal.Header closeButton>
                        <Modal.Title id="contained-modal-title">
                            {modal.title}
                        </Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        {modal.content}
                    </Modal.Body>
                    <Modal.Footer>
                        <Button onClick={() => this.setState({ show: false })}>
                            Close
                        </Button>
                    </Modal.Footer>
                </Modal>
                {/* --> end modal instance <-- */}
            </Carousel.Item>
        );
    }
}

接下来,我会在我的Carousel组件中使用它,如下所示

class MyCarousel extends Component {
    constructor() {
        super();

        this.state = {
            items: [
                {
                    caption: "blah 1",
                    title: "blah 1",
                    src: "/path/to/image",
                    alt: "blah 1"
                },
                {
                    caption: "blah 2",
                    title: "blah 2",
                    src: "/path/to/another/image",
                    alt: "blah 2"
                }
            ]
        };

        this.renderItems = this.renderItems.bind(this);
    }

    renderItems() {
        const { items } = this.state;

        items.map(item => {
            const modal = {
                title: item.title,
                content: item.caption
            };

            return <Item key={item.title} {...item} modal={modal} />;
        });
    }

    render() {
        return (
            <Carousel>
                {this.renderItems()}
            </Carousel>
        );
    }
}