检测点击外部组件

时间:2019-01-23 14:19:04

标签: javascript reactjs

这是我的代码:

export default ({user, showFriendsInvitations}) => {
    const handleBlur = () => {
        console.log('blur');
        setShowFriendInvitations(false);
    };
    const handleClick = () => {
        console.log(showFriendsInvitations)
        setShowFriendInvitations(!showFriendsInvitations);
    };

    const invites = user.friends.filter(f => f.accepted === false && f.blocked === true);
    return (
        <div className='inline iconBtnContainer'>
            {invites.length > 0 ?
                <div className='notificationContainer'>
                    <p>{invites.length}</p>
                </div>
                : null}

            <button className='iconBtn' onClick={handleClick}>
                 <CustomSvg/>
            </button>

            <div className='newInvitationFriendsDropdown' style={{background: 'yellow'}} onBlur={handleBlur}>
                {invites.length > 0 ?
                    <div className='newInvitationFriendsForm displayCenter'>
                        {invites.map(i => <div key={i}><FriendInvitationContainer invite={i}/></div>)}
                    </div> : <div className='newInvitationFriendsForm displayCenter'>Brak nowych zaproszeń</div>}
            </div>

            {showFriendsInvitations === true ? <FriendsInvitesContainer invites={invites}/> : null}
        </div>
    )
}

这是它的样子:

enter image description here

我要实现的目标:当用户单击黄色div之外的任何位置时,(className =“ newInvitationFriendsDropdown”)我需要将setShowFriendInvitations设置为false。我尝试使用handleBlur进行此操作,但它既未注册onBlur也未注册onFocus

我该如何做?

0 个答案:

没有答案