首页 > 解决方案 > 做出反应。onClick 事件未触发

问题描述

在我的导航栏中,我有一个按钮,单击该按钮将显示子菜单(项目列表)。每个项目都是它们自己的子组件,单击时我希望它们触发一个事件。onClick 事件侦听器根本没有响应。但是,其他鼠标事件也适用(onMouseEnter、onMouseOut 等)。任何人都可能知道发生了什么?

子组件:NotificationItem.js

import React from "react"
import { connect } from "react-redux"
import { updateNotification } from "../../actions/notificationActions"

class NotificationItem extends React.Component{
constructor(props){
    super(props)

    this.handleOnClick = this.handleOnClick.bind(this)
}

handleOnClick = (event) => {
    console.log("clicked")
    // let notificationId = this.props.notification._id
    // this.props.updateNotification(notificationId)
}

render(){
    let {avatar, description, seen} = this.props.notification
    return(
        <div
            onClick={this.handleOnClick}
            className="d-flex notification-wrapper" 
            style={ seen ? (
                { width: "250px", whiteSpace: "normal", padding: "0.5rem" } 
                ):( { width: "250px", whiteSpace: "normal", padding: "0.5rem", backgroundColor: "#d7e2f4" }
                )
            }
            >
            <div>
                <img src={avatar} style={{ width: "25px"}} className="mr-2 rounded-circle"/>
            </div>
            <div>
                {description}
            </div>
        </div>
    )
}

}

父组件:NotificationFeed.js

import React from "react"
import { connect } from "react-redux"
import NotificationItem from "./NotificationItem"

class NotificationFeed extends React.Component{
constructor(props){
    super(props)
}

render(){
    let notifications = this.props.notification.notifications
    return(
        <div className="dropdown-menu">
            {notifications.map((notification, index) => {
                return(
                    <div key={index}>
                        <NotificationItem notification={notification}/>
                    </div>
                )
            })}         
        </div>
    )
}
}

const mapStateToProps = (state) => {
return{
    notification: state.notification
}
}

export default connect(mapStateToProps)(NotificationFeed)

编辑:我注意到可能有帮助的东西。我正在使用引导类来创建这个下拉切换效果。单击其中一项时,子菜单会立即关闭,而不会在组件上触发我想要的事件处理程序。

                <span className="dropdown" id="notifications-dropdown">
                <Link to="#" className="nav-link text-light dropdown-toggle" data-toggle="dropdown">
                    <span 
                        key={Math.random()}
                    >
                        <i className="fa fa-bell"></i>
                    </span> { windowWidth < 576 && "Notifications"}

                    <NotificationFeed/>

                </Link>
                </span>

标签: javascriptreactjs

解决方案


对于那些仍然感兴趣的人,这是 Bootstrap 的一个问题。因为元素是在 Bootstrap 下拉列表中创建的,所以它有一些我看不到的逻辑。每当我单击一个元素时,下拉菜单会在事件处理程序触发之前关闭。

选择创建我自己的下拉列表。谢谢大家!


推荐阅读