react next.js点击任何区域关闭弹框,以点击按钮弹出下拉菜单为例

react next.js点击任何区域关闭弹框,以点击按钮弹出下拉菜单为例_第1张图片

 

import { useState,useEffect,useCallback,useRef,memo} from 'react'
import Icon from '../icon';
import  '../../public/css/ui/drop_down.css';
function drop_down(props){
    const {menu,name,icon,current}=props;

//menu=[{
//   id:0,
//   name_en:"全部"
//},id:1,name_en:"菜单一"}]
//name:默认名
//icon
//current为当前选中项索引

    const bodyBox = useRef(null);
    const [isbtn, setisbtn] = useState(0);
    const [menuIndex, setmenuIndex] = useState(0);
    function bindshow(e){
        let isbtn1=isbtn?0:1
        setisbtn(isbtn1);
    }
    const onClickOutsideHandler = useCallback(
        (e) => {
            if(bodyBox.current){
                if(!bodyBox.current.contains(e.target)){
                    setisbtn(0)
            }}
        },[]
      );
      function Checktype(index, e){
          console.log(index,e)
          setmenuIndex(index)
         setisbtn(0);
        //console.log("menu[index]",menu[index])
        e.nativeEvent.stopImmediatePropagation();
        props.getChildValue && props.getChildValue(menu[index]);
      }
    useEffect(()=>{
        if(current && current!=undefined){
            setmenuIndex(current);
        }
        document.addEventListener('click', onClickOutsideHandler);
    },[])
    return(
        <>
        
{menuIndex==0 ?name:menu[menuIndex].name_en}
{isbtn?
{menu.map((item,index)=>(
{item.name_en}
))}
:''}
) } export default memo(drop_down) //用法:
//drop_down.css
.ui_drop_down_btn_bg{
    position: relative;
}
.ui_drop_down_btn{
    padding:6px 10px;
    background: #f5f5f5;
    border-radius: 5px;
    margin-right: 20px;
    display: inline-flex;
    justify-content: center;
    align-items: center;

    
}
.ui_drop_down_btn .ui_icon{
    display: block;
    height: 24px;
    line-height: 24px;
    font-size: 24px;
    margin-right: 6px;
}
.ui_drop_down_btn .arrow{margin-left: 6px;}

.ui_drop_down_menu{
    width: 250px;
    position: absolute;
    left: 0;
    top: 50px;
    background: #ffffff;
    border-radius: 5px;
    background-color: rgba(255, 255, 255, 1);
    box-shadow: 0px 15px 50px -25px rgba(106, 106, 106, 1);
    border: 1px solid rgba(42, 42, 42, 1);
    padding: 15px 0px;
    z-index: 99;
}

.ui_drop_down_menu_li{
    height: 36px;
    line-height: 36px;
    padding: 0 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.ui_drop_down_menu_li .icon{display: none;font-size: 16px;}
.ui_drop_down_menu_li_on{
    background: #f5f5f5;
}
.ui_drop_down_menu_li_on .icon{display: block;}
.ui_drop_down_menu_li:hover{background: #f5f5f5;}

 

你可能感兴趣的:(next.js,react-next)