在 reactjs 中悬停时显示组件

IT技术 css reactjs
2021-05-20 08:09:58

我创建了几个带有特定内容标题的部分。

我想在悬停在不同部分上方时显示一个简短的预览。

有谁知道如何创建带有条件渲染react组件的 hoverActionHandler ?

1个回答

您可以使用onMouseOveronMouseOut来更改状态并根据状态值有条件地渲染组件。

看看它在行动:

  • 钩子实现:https ://codesandbox.io/s/react-hover-example-hooks-0to7u
  • 类实现:https ://codesandbox.io/s/XopkqJ5oV

挂钩:

import React, { useState } from "react";
import { render } from "react-dom";

const HoverableDiv = ({ handleMouseOver, handleMouseOut }) => {
  return (
    <div onMouseOver={handleMouseOver} onMouseOut={handleMouseOut}>
      Hover Me
    </div>
  );
};

const HoverText = () => {
  return (
    <div>
      Hovering right meow!
      <span role="img" aria-label="cat">
        🐱
      </span>
    </div>
  );
};

const HoverExample = () => {
  const [isHovering, setIsHovering] = useState(false);
  const handleMouseOver = () => {
    setIsHovering(true);
  };

  const handleMouseOut = () => {
    setIsHovering(false);
  };

  return (
    <div>
      {/* Hover over this div to hide/show <HoverText /> */}
      <HoverableDiv
        handleMouseOver={handleMouseOver}
        handleMouseOut={handleMouseOut}
      />
      {isHovering && <HoverText />}
    </div>
  );
};

class:

import React, { Component } from "react";
import { render } from "react-dom";

const HoverableDiv = React.memo(({ handleMouseOver, handleMouseOut }) => {
  return (
    <div onMouseOver={handleMouseOver} onMouseOut={handleMouseOut}>
      Hover Me
    </div>
  );
});

const HoverText = () => {
  return (
    <div>
      Hovering right meow!
      <span role="img" aria-label="cat">
        🐱
      </span>
    </div>
  );
};

class HoverExample extends Component {
  constructor(props) {
    super(props);
    this.handleMouseOver = this.handleMouseOver.bind(this);
    this.handleMouseOut = this.handleMouseOut.bind(this);
    this.state = {
      isHovering: false
    };
  }

  handleMouseOver() {
    this.setState(() => ({
      isHovering: true
    }));
  }

  handleMouseOut() {
    this.setState(() => ({
      isHovering: false
    }));
  }

  render() {
    return (
      <div>
        {/* <HoverText /> gets shown when mouse is over <HoverableDiv /> */}
        <HoverableDiv
          handleMouseOver={this.handleMouseOver}
          handleMouseOut={this.handleMouseOut}
        />
        {this.state.isHovering && <HoverText />}
      </div>
    );
  }
}