简体   繁体   中英

fade in fade out on hover in reactjs

I am trying to create component in react. I am on learning mode. So may be I am doing totally wrong. Below is my code

My Code on sandbx

https://codesandbox.io/s/pedantic-bush-roiv6?fontsize=14&hidenavigation=1&theme=dark

class MegaMenu extends React.Component {
  public render() {
    return (
      <div className={styles.MegaMenu}>
        <div className={styles["menu-container"]}>
          <div className={styles.menu}>
            <MenuList Options={menus} />
          </div>
        </div>
      </div>
    )
  }
}

const MenuList = (props: IMenuListProps) => {
  return (
    <ul>
      {
        props.Options.map((Option: IMenu, index: number) => (
          <li key={index} className={(Option.subitem && Option.subitem.length > 0) ? styles["menu-dropdown-icon"] : styles["normal-sub"]}>
            <a href={Option.link}>{Option.name}</a>
            {/* Base Case */}
            {
              (Option.subitem && Option.subitem.length > 0) &&
              <MenuList Options={Option.subitem} />
            }
          </li>
        ))
      }
    </ul>
  )
}

I was trying something as in jQuery if like have children

$(".menu > ul > li").hover(
        function (e) {
            if ($(window).width() > 943) {
                $(this).children("ul").fadeIn(150);
                e.preventDefault();
            }
        }, function (e) {
            if ($(window).width() > 943) {
                $(this).children("ul").fadeOut(150);
                e.preventDefault();
            }
        }
    );

How we can do in react.

This isn't a full answer solving your problem, just some direction you might want to take:

What I would do is make <MenuList> a stateful component rather than functional, and store a bit of state about whether it was being hovered or not. On the <ul> do an onMouseEnter callback that sets the hovered state and an onMouseLeave callback that unsets it (sets it to false), and pass down a prop to the next MenuList about if it should show or not.

You can choose a variety of options to deal with that prop. If animation isn't necessary, you can simply add a style property to the ul if the props.show === true :

let styles = {};
if (this.props.show) {
  styles = {display:block}
}
...
<ul style={styles}>
...

If animation is required... well then good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM