首页 > 解决方案 > 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>

            
        )
    }
}

标签: reactjstypescriptreact-dom

解决方案


在 NotificationList组件上添加ref不会为您提供其中呈现的 DOM 元素的引用,您需要将 ref 传递给divinsideNotificationList

<NotificationList innerRef={this.container} />

并在 NotificationList

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

PS 一个简短的解决方案是使用ReactDOM.findDOMNode(this.container.current),但不再建议在 React 中使用


推荐阅读