0

Я использую состояние все работает нормально, за исключением модального окна. Внутри состояния, я использую объекты, которые нормально отображаются (вы можете посмотреть на скриншот https://ibb.co/YBg30NW ) пожалуйста,обратите внимание на кнопки под названием "Открытый модал", когда вы нажмете на одну их этих кнопок, модальное окно открывается и должны отображать название языка программирования, как показано на скриншоте. Проблема в том, что при открытии модального окна отображается только одно и то же название языков программирования "CSS" https://ibb.co/J5jrZF0 независимо от того, какую кнопку я нажимаю, чтобы открыть модальное окно, отображается только "CSS", как я могу решить эту проблему?

 import React from "react"
    import cnStyle from "./ContentCourses.module.css"
    import python from "./Icons/pyhton.png"
    import cPlusPlus from "./Icons/c++.png"
    import JavaScript from "./Icons/JavaScript.png"
    import swift from "./Icons/swift.png"
    import HTML from "./Icons/HTML.png"
    import CSS from "./Icons/CSS.png"
    import Modal from 'react-modal';
    
    const customStyles = {
        content: {
            top: '50%',
            left: '50%',
            right: 'auto',
            bottom: 'auto',
            marginRight: '-50%',
            transform: 'translate(-50%, -50%)'
        }
    };
    
    Modal.setAppElement('#root');
    
    export class ContentCourses extends React.Component {
    
        constructor() {
            super();
            this.state = {
                languageInfo: [
                    {
                        languageName: "Python 3",
                        about: `
                        Learn Python, one of today's most in-demand programming languages on-the-go!
                        Practice writing Python code, collect points, & show off your skills now!`,
                        Learners: 30045,
                        Lessons: 87,
                        Quizzes: 271,
                        icon: python,
                    },
    
                    {
                        languageName: "JavaScript",
                        about: `
                        Learn all the basic features of JavaScript, including making your website more interactive,
                        changing website content, validating forms, and so much more.`,
                        Learners: 42123,
                        Lessons: 42,
                        Quizzes: 321,
                        icon: JavaScript,
                    },
    
                    {
                        languageName: "C++",
                        about: `
                        Our C++ tutorial covers basic concepts, data types, arrays, pointers, conditional statements,
                        loops, functions, classes, objects, inheritance, and polymorphism.`,
                        Learners: 53241,
                        Lessons: 23,
                        Quizzes: 451,
                        icon: cPlusPlus,
                    },
    
                    {
                        languageName: "Swift",
                        about: `
                        Learn all the main concepts of Swift programming and apply your newly gained knowledge
                        to create your own, fully functioning iOS app!`,
                        Learners: 63211,
                        Lessons: 54,
                        Quizzes: 623,
                        icon: swift,
                    },
    
                    {
                        languageName: "HTML",
                        about: `
                        This FREE course will teach you how to design a web page using HTML.
                        Complete a series of hands-on exercises and practice while writing real HTML code.`,
                        Learners: 18024,
                        Lessons: 32,
                        Quizzes: 962,
                        icon: HTML,
                    },
    
                    {
                        languageName: "CSS",
                        about: `
                        Our CSS course will teach you how to control the style & layout of websites.
                        Complete a series of exercises and practice while filling out actual CSS templates.`,
                        Learners: 58932,
                        Lessons: 46,
                        Quizzes: 125,
                        icon: CSS,
                    },
    
                ],
    
                modalIsOpen: false,
                setIsOpen: false,
            }
        }
    
        openModal() {
            this.setState({setIsOpen: true})
            this.setState({modalIsOpen: true})
        }
    
        afterOpenModal() {
            // references are now sync'd and can be accessed.
            // subtitle.style.color = '#f00';
        }
    
        closeModal() {
            this.setState({setIsOpen: false})
            this.setState({modalIsOpen: false})
        }
    
        render() {
            var subtitle;
            const resultsRender = [];
    
            for (var i = 0; i < this.state.languageInfo.length; i += 2) {
                resultsRender.push(
                    <div className={cnStyle.clearfix}>
                        {
                            this.state.languageInfo.slice(i, i + 2).map((item, index) => {
                                    return (
                                        <div key={index} className={cnStyle.ContentVeryHeadlineBlock}>
    
                                            <div className={cnStyle.ContentHeadlineBlock}>
                                                <div className={cnStyle.ContentCoursesBlock}>
    
                                                    <div style={{marginRight: '25px'}} className={cnStyle.courseIconBlock}>
                                                        <img className={cnStyle.courseIcon} src={item.icon} alt=""/>
                                                    </div>
    
                                                    <div>
                                                        <div className={cnStyle.courseName}>
                                                            <h3>{item.languageName}</h3>
                                                        </div>
    
                                                        <div>
                                                            <p style={{color: 'dimgrey'}}>
                                                                {item.about}
                                                            </p>
                                                        </div>
                                                    </div>
                                                </div>
    
    
                                                <div className={cnStyle.buttonMoreBlock}>
                                                    <div>
                                                        <button onClick={this.openModal.bind(this)}>Open Modal</button>
                                                        <Modal
                                                            isOpen={this.state.modalIsOpen}
                                                            onAfterOpen={this.afterOpenModal.bind(this)}
                                                            onRequestClose={this.closeModal.bind(this)}
                                                            style={customStyles}
                                                            contentLabel="Example Modal"
                                                        >
    
                                                            <h2 ref={_subtitle => (subtitle = _subtitle)}>{item.languageName}</h2>
                                                            <button onClick={this.closeModal.bind(this)}>close</button>
                                                            <div>I am a modal</div>
                                                            <form>
                                                                <input />
                                                                <button>tab navigation</button>
                                                                <button>stays</button>
                                                                <button>inside</button>
                                                                <button>the modal</button>
                                                            </form>
                                                        </Modal>
                                                    </div>
                                                </div>
    
                                            </div>
    
                                            <div className={cnStyle.moreInformation}>
                                                <div>
                                                    <p>Learners</p>
                                                    <p className={cnStyle.learnQuantity}>{item.Learners}</p>
                                                </div>
                                                <div>
                                                    <p>Lessons</p>
                                                    <p className={cnStyle.learnQuantity}>{item.Lessons}</p>
                                                </div>
                                                <div>
                                                    <p>Quizzes</p>
                                                    <p className={cnStyle.learnQuantity}>{item.Quizzes}</p>
                                                </div>
                                            </div>
                                        </div>
                                    );
                                }
                            )
                        }
                    </div>
                );
            }
    
            return (
                <div>
                    {resultsRender}
                </div>
            );
        }
    }

1 ответ 1

0

у вас общее состояние для всех окон, они все одновременно открываются и закрываются (последний перекрывает все предыдущие). Нужно каждому разделу дать свои флаги на состояние модального окна.

export class ContentCourses extends React.Component {

    constructor() {
        super();
        this.state = {
            languageInfo: [
                {
                    id:"1",
                    languageName: "Python 3",
                    about: `
                    Learn Python, one of today's most in-demand programming languages on-the-go!
                    Practice writing Python code, collect points, & show off your skills now!`,
                    Learners: 30045,
                    Lessons: 87,
                    Quizzes: 271,
                    modalIsOpen: false,
                    setIsOpen:false,
                },

                {
                    id:"2",
                    languageName: "JavaScript",
                    about: `
                    Learn all the basic features of JavaScript, including making your website more interactive,
                    changing website content, validating forms, and so much more.`,
                    Learners: 42123,
                    Lessons: 42,
                    Quizzes: 321,
                    modalIsOpen: false,
                    setIsOpen:false,
                },

                {
                    id:"3",
                    languageName: "C++",
                    about: `
                    Our C++ tutorial covers basic concepts, data types, arrays, pointers, conditional statements,
                    loops, functions, classes, objects, inheritance, and polymorphism.`,
                    Learners: 53241,
                    Lessons: 23,
                    Quizzes: 451,
                    modalIsOpen: false,
                    setIsOpen:false,
                },

                {
                    id:"4",
                    languageName: "Swift",
                    about: `
                    Learn all the main concepts of Swift programming and apply your newly gained knowledge
                    to create your own, fully functioning iOS app!`,
                    Learners: 63211,
                    Lessons: 54,
                    Quizzes: 623,
                    modalIsOpen: false,
                    setIsOpen:false,
                },

                {
                    id:"5",
                    languageName: "HTML",
                    about: `
                    This FREE course will teach you how to design a web page using HTML.
                    Complete a series of hands-on exercises and practice while writing real HTML code.`,
                    Learners: 18024,
                    Lessons: 32,
                    Quizzes: 962,
                    modalIsOpen: false,
                    setIsOpen:false,
                },

                {
                    id:"6",
                    languageName: "CSS",
                    about: `
                    Our CSS course will teach you how to control the style & layout of websites.
                    Complete a series of exercises and practice while filling out actual CSS templates.`,
                    Learners: 58932,
                    Lessons: 46,
                    Quizzes: 125,
                    modalIsOpen: false,
                    setIsOpen:false,

                }
            ]
        }
    }

    openModal(i) {
      const languageInfo = [...this.state.languageInfo];
      languageInfo[i] = {...languageInfo[i],setIsOpen: true,modalIsOpen: true}
        this.setState({languageInfo});
    }

    afterOpenModal() {
        // references are now sync'd and can be accessed.
        // subtitle.style.color = '#f00';
    }

    closeModal = (i)=>()=>{
      const languageInfo = [...this.state.languageInfo];
      languageInfo[i] = {...languageInfo[i],setIsOpen: false,modalIsOpen: false}
        this.setState({languageInfo});
    }

    render() {
        var subtitle;
        const resultsRender = [];

        for (var i = 0; i < this.state.languageInfo.length; i += 2) {
            resultsRender.push(
                <div key={i}>
                    {
                        this.state.languageInfo.slice(i, i + 2).map((item, index) => {
                                return (
                                    <div key={index}>    
                                        <div>
                                            <div>
                                                <div style={{marginRight: '25px'}}>
                                                    <img src={item.icon} alt=""/>
                                                </div>

                                                <div>
                                                    <div>
                                                        <h3>{item.languageName}</h3>
                                                    </div>

                                                    <div>
                                                        <p style={{color: 'dimgrey'}}>
                                                            {item.about}
                                                        </p>
                                                    </div>
                                                </div>
                                            </div>


                                            <div>
                                                <div>
                                                    <button onClick={this.openModal.bind(this,index)}>Open Modal</button>
                                                    <Modal
                                                        isOpen={item.modalIsOpen}
                                                        onAfterOpen={this.afterOpenModal.bind(this)}
                                                        onRequestClose={this.closeModal(index)}
                                                        style={customStyles}
                                                        contentLabel="Example Modal"
                                                    >

                                                        <h2 ref={_subtitle => (subtitle = _subtitle)}>{item.languageName}</h2>
                                                        <button onClick={this.closeModal(index)}>close</button>
                                                        <div>I am a modal</div>
                                                        <form>
                                                            <input />
                                                            <button>tab navigation</button>
                                                            <button>stays</button>
                                                            <button>inside</button>
                                                            <button>the modal</button>
                                                        </form>
                                                    </Modal>
                                                </div>
                                            </div>

                                        </div>

                                        <div>
                                            <div>
                                                <p>Learners</p>
                                                <p>{item.Learners}</p>
                                            </div>
                                            <div>
                                                <p>Lessons</p>
                                                <p>{item.Lessons}</p>
                                            </div>
                                            <div>
                                                <p>Quizzes</p>
                                                <p>{item.Quizzes}</p>
                                            </div>
                                        </div>
                                    </div>
                                );
                            }
                        )
                    }
                </div>
            );
        }

        return (
            <div>
                {resultsRender}
            </div>
        );
    }
}
1
  • Спасибо что обратили внимание, я использовал ваш вариант, но в таком случае работает только Python и JavaScript, остальное не работает, думаю что это из за цикла for (var i = 0; i < this.state.languageInfo.length; i += 2)
    – Synchro
    20 ноя 2020 в 18:20

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.