javascript - 做出反应。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>
解决方案
对于那些仍然感兴趣的人,这是 Bootstrap 的一个问题。因为元素是在 Bootstrap 下拉列表中创建的,所以它有一些我看不到的逻辑。每当我单击一个元素时,下拉菜单会在事件处理程序触发之前关闭。
选择创建我自己的下拉列表。谢谢大家!
推荐阅读
- python - 如何使用 AWS SessionToken 从 pyspark 中的 S3 读取?
- c# - 将后台工作人员传递给 VSTO Excel 插件中的另一个类
- r - 生成圆的点
- sql - 根据另一列的值排除从具有特定值的 case 语句派生的行
- jhipster - 在 JHipster 项目中手动添加实体
- typescript - Angular 5过滤器>地图>将图像分配给OpenWeather对象并在屏幕上显示不显示
- variables - 在范围循环中增加 struct var
- c - C - 关于字符串的预处理器声明
- enums - 如何在 Chapel 中声明 ENUM?
- yaml - 如何强制数组中的对象键名