reactjs - ref.current.contains 不是 React 中的函数
问题描述
我在 React 中做了一个下拉切换。我的下拉菜单工作得很好。但是当我尝试在下拉菜单之外单击时关闭下拉菜单。它显示错误。我使用 ref 来查找容器元素。示例代码
class Search extends React.Component{
constructor()
{
super()
this.state={
notificationStatus:false,
isFocus:false
}
this.container=React.createRef()
}
toggleNotification=()=>
{
this.setState({notificationStatus:!this.state.notificationStatus});
}
componentDidMount() {
document.addEventListener("mousedown", this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener("mousedown", this.handleClickOutside);
}
handleClickOutside = event => {
if(this.container.current)
{
if (this.container.current && !this.container.current.contains(event.target)) {
this.setState({
notificationStatus: false,
});
}
}
};
render()
{
const {isFocus,notificationStatus}=this.state;
return(
<div>
<div className="col-md-1 col-sm-1 bell-container flex all-center relative">
<img src={bell} onClick={this.toggleNotification} alt="bell icon" />
</div>
{
notificationStatus ? <NotificationList ref={this.container} /> : null
}
</div>
)
}
}
解决方案
在 NotificationList组件上添加ref不会为您提供其中呈现的 DOM 元素的引用,您需要将 ref 传递给div
insideNotificationList
<NotificationList innerRef={this.container} />
并在 NotificationList
class NotificationList extends React.Component {
render() {
<div ref={this.props.innerRef}>{/* */}</div>
}
}
PS 一个简短的解决方案是使用ReactDOM.findDOMNode(this.container.current)
,但不再建议在 React 中使用
推荐阅读
- azure-functions - 如何使用 Azure Functon 将 blob 触发器获取的文件保存到 SFTP 服务器
- angular - 角度 RouteReuseStrategy 滚动位置保持
- xml - How to get perfect match text using XPath selector?
- android - 从 Firebase 云消息传递控制台发送带有 URL 的 Flutter 推送通知
- github - GitHub:接受当前更改和传入更改之间的区别
- javascript - CredentialsError:“配置中缺少凭据”,即使设置了凭据
- sql-server - 错误 CREATE 语句 SQL SERVER : FK PK
- javascript - 数数 setInterval 内数组中的元素:Javascript
- html - 悬停时的图像缩放不适用于:after
- css - 有没有办法在 mat-datepicker 中垂直居中 datepicker?