反应ref.current.contains不是一个函数

我做了一个下拉切换反应。我的下拉菜单工作得很好。但是,当我尝试在下拉菜单外部单击时关闭下拉菜单时。显示错误。我使用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>


        )
    }
}

评论
  • 满足ni
    满足ni 回复

    Adding a ref on NotificationList component will not give you the reference of the DOM element rendered in it, you need to pass down the ref to the div within NotificationList

    <NotificationList innerRef={this.container} />
    

    并在NotificationList中

    class NotificationList extends React.Component {
       render() {
          <div ref={this.props.innerRef}>{/* */}</div>
       }
    }
    

    P.S. a short solution is to use ReactDOM.findDOMNode(this.container.current) but its not longer recommended to use in React