我已经创建了几个章节,标题是具体内容.

我想展示一个在不同区域上方悬停的简短预览.

有人知道如何创建带有条件呈现的Resact组件的hoverActionHandler吗?

推荐答案

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

在行动中看到它:

钩子:

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>
  );
};

课程:

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>
    );
  }
}

Reactjs相关问答推荐

react 表复选框不对任何操作做出react

条件索引路由

Reaction-路由v6动态路径RegExp

对搜索引擎优化来说,react 头盔的异步足够了吗?

React Router:在没有手动页面刷新的情况下,路由不会更新内容

GitHub页面配置

无法在REACTION TANSTACK查询中传递参数

阻止组件更新的多分派Redux Thunk或setState是否有任何问题

React useContext 的未定义返回值

无法使用react-hook-form和react-places-autocomplete在字段中输入值

在Vite React上获取Amplify的环境变量

React - 如何重定向页面以显示数据修改?

React Native 背景动画反转

Reactjs 表单未反映提交时的更改

响应式媒体 React Tailwind

如何从 React Redux store 中删除特定项目?

getAttribute 函数并不总是检索属性值

加密 Django Rest Framework API 响应 + 解密响应应用程序中的响应

使具有 onClick 免疫的父元素的子元素

reactjs useEffect 获取数据后的清理功能