我在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>
)
}
}
添加一个 在通知列表上的编号 组件不会给你渲染的DOM元素的引用,你需要将引用传递给 div
内 NotificationList
<NotificationList innerRef={this.container} />
而在NotificationList中
class NotificationList extends React.Component {
render() {
<div ref={this.props.innerRef}>{/* */}</div>
}
}
P.S. 一个简单的解决方案是使用 ReactDOM.findDOMNode(this.container.current)
但其不再推荐在React中使用。