未捕获的TypeError:.includes不是React Ref的函数

时间:2018-11-01 21:50:55

标签: javascript reactjs

我正在尝试制作一个菜单,单击该菜单即可显示。这很好。但是我希望每当选择除原始菜单或项目列表以外的任何内容时,菜单都关闭。但是,当我这样做时,它会返回错误

Uncaught TypeError: _this.dropdownMenu.includes is not a function
    at HTMLDocument.eval (FeedItem.jsx:277)

视觉

enter image description here

代码

import React, { Component } from 'react'
import styled from 'styled-components';

const OptionMenu = styled.div `
    position: absolute;
    top: 20px;
    left: -130px;
    display: ${props => props.showMenu ? 'flex' : 'none'};
    flex-direction: column;
    width: 150px;
    background: #FFFFFF;
    border: 1px solid #EEEFEF;
    box-shadow: 0 2px 2px 0 rgba(0,0,0,.14), 0 3px 1px -2px rgba(0,0,0,.2), 0 1px 5px 0 rgba(0,0,0,.12);
    z-index: 100;
`;

const OptionItem = styled.div `
    color: #414141;
    font-size: 18px;
    cursor: pointer;
    padding: 10px 5px;
    transition: .2s;

    &:hover {
        background-color: #F2F2F2;
    }
`;


class FeedItem extends Component {
    constructor() {
        super();

        this.state = {
            showMenu: false
        }

        this.dropdownMenu = React.createRef();
    }

    showMenu = (e) => {
        this.setState({ showMenu: true }, () => {
          document.addEventListener('click', this.closeMenu);
        });
    }

    closeMenu = (e) => {
        if(!this.dropdownMenu.includes(e.target)) {
            console.log('yes')

            this.setState({ showMenu: false }, () => {
                document.removeEventListener('click', this.closeMenu);
            });
        }
    }

    render(props) {
        const { showMenu } = this.state;

        return(
            <Container item={this.props.id}>
                    <UserOptions onClick={() => this.showMenu()} ref={this.dropdownMenu}>

                        <OptionMenu showMenu={showMenu}>
                            <OptionItem>Share</OptionItem>
                            <OptionItem>Something</OptionItem>
                        </OptionMenu>
                    </UserOptions>
            </Container>
        );
    }
}

export default FeedItem;

我正在使用样式组件,这可能是个问题吗?另外,我还仔细研究了容器的大部分部件,并刚刚离开了问题区域。

1 个答案:

答案 0 :(得分:1)

includesStringArray方法,而不是Node方法。

您可以改用contains

closeMenu = (e) => {
    if (!this.dropdownMenu.current.contains(e.target)) {
        console.log('yes')

        this.setState({ showMenu: false }, () => {
            document.removeEventListener('click', this.closeMenu);
        });
    }
}