【问题标题】:Event Propagation in ReactReact 中的事件传播
【发布时间】:2018-02-15 21:19:10
【问题描述】:

我有一个模态。如果我点击背景,我希望模态消失。如果我单击模态表单,我不希望它消失。存在表单上的触发事件冒泡到容器背景并关闭 div 的问题。如果单击内部 div,我希望模态不会关闭。

(clearQuiz 使模态消失)

这里是组件:

import React from 'react'; 
import { connect } from 'react-redux'; 
import { Redirect } from 'react-router-dom'; 
import { clearQuiz } from '../../actions/quiz'; 
import './Quiz.css'; 

export class Quiz extends React.Component {

    handleClose(e) {
        e.stopPropagation();
        this.props.dispatch(clearQuiz()); 
    }


    render() {  

        let answers = this.props.answers.map((answer, idx) => (
            <li key={idx}>{answer}</li>
        )); 

        if (this.props.usingQuiz) {
            return ( 
                <div className="quiz-backdrop" onClick={e => this.handleClose(e)}>
                    <div className="quiz-main">
                        <h2>{this.props.title} Quiz</h2>
                        <h3>{this.props.currentQuestion}</h3>
                        <ul>
                        {answers}
                        </ul>
                    </div>
                </div>
            )  
        } 
        else {
            return <Redirect to="/" />; 
        }      
    }
}

const mapStateToProps = state => ({
    usingQuiz: state.currentQuestion, 
    answers: state.answers, 
    currentQuestion: state.currentQuestion, 
    title: state.currentQuiz, 

}); 

export default connect(mapStateToProps)(Quiz); 

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    根本不要通过这个活动!试试onClick={()=&gt;this.handleClose()}

    【讨论】:

    • 所以我这样做了,我得到了这个错误:TypeError: Cannot read property 'stopPropagation' of undefined
    • 无法识别方法中的 e 是什么
    • 对不起,我应该澄清一下。从 handleClose() 中删除参数 e 和 e.stopPropagation() 。
    • clearQuiz 功能绝对有效。我现在有这样的方法:
    • handleClose() { this.props.dispatch(clearQuiz()); }
    猜你喜欢
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    相关资源
    最近更新 更多