简体   繁体   中英

ReactJS modal window

I have no idea how to make my app work. I have a component ContactAdd that onClick must render component ModalWindow . ModalWindow has a parameter isOpened={this.state.open} . How to control this state from parent component?

import React from 'react';

import ContactAddModal from './ContactAddModal.jsx';

import './ContactAdd.css';

export default class ContactAdd extends React.Component {
    constructor(props){
        super(props);
    }
    render() {
        return (
            <div className="add-contact" onClick={ ??????? }>
                <img src="./img/add.png" />
                <ContactAddModal/>
            </div>
        )
    }
}




import React from 'react';

export default class ContactAddModal extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            show: false,
        };
        this.handleCloseModal = this.handleCloseModal.bind(this);
    }

    handleCloseModal () {
        this.setState({ show: false });
    }

    render() {
        return (
            <div className="modal" isOpened={this.state.show}>
                <button onClick={this.handleCloseModal}>Close Modal</button>
            </div>
        )
    }

Making the modal a stateless component might be simpler here. The tradeoff being that you would have to handle the closing for every modal, which I think is acceptable. This answer is just an option and by no means an absolute truth.

It could look something like that

export default class ContactAdd extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            showModal: true
        };
        this.hideModal = this.hideModal.bind(this);
    }

    hideModal() {
        this.setState({
            showModal: false
        });
    }

    render() {
        return (
            <div className="add-contact">
                <img src="./img/add.png" />
                <ContactAddModal handleClose={this.hideModal} isOpened={this.state.showModal} />
            </div>
        )
    }
}

Now the modal:

export default class ContactAddModal extends React.Component {
    render() {
        return (
            <div className="modal" isOpened={this.props.isOpened}>
                <button onClick={this.props.handleClose}>Close Modal</button>
            </div>
        )
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM