首页 > 解决方案 > 用 react js 改变不透明度和动画

问题描述

我用react开始了一个简单的项目。在我的项目中,我有一个段落,当鼠标悬停在段落上时(鼠标进入事件),段落下方会出现一个正方形,当从段落悬停时(鼠标离开事件)该正方形消失。但这发生了如此之快,所以我想顺利地改变它,我想使用不透明度并将其从 0 更改为 1 并在我的事件发生时反转。但我不知道如何用动画来改变不透明度。

这是我的appjs

import './index.css';
import React, {useState} from "react";

function App() {
    const [isShowSquare, setIsShowSquare] = useState(false);
    const showSquare = () => {
        setIsShowSquare(true);
    }
    const hideSquare = () => {
        setIsShowSquare(false);
    }
    return (
        <div>
            <p onMouseEnter={showSquare} onMouseLeave={hideSquare} style={{display:'inline-block'}}>Hover Me</p>

            {isShowSquare ?
                <div className='square'>
                </div>
                : null
            }

        </div>

    );
}

export default App;

这是我的 index.css

*{
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.square{
  width: 50px;
  height: 50px;
  background-color: #61dafb;
}

如果有人可以帮助我,我将不胜感激

标签: javascriptcssreactjstypescriptmouseevent

解决方案


这是一种不使用的方法useState。我不知道这部分是否重要,但看看我的 沙盒

首先,您需要一个 css 类来定义方法的不透明度以及它将花费多少时间。此外,您的第一square堂课应该有 opacity: 0,表示不可见。

当鼠标悬停在文本上时,您将额外的类添加到元素中。

  const showSquare = () => {
    div.current.classList.add("square-full");
  };

  const hideSquare = () => {
    div.current.classList.remove("square-full");
  };

.square.square-full {
  opacity: 0.5;
  transition: opacity 1s ease-out;
}

.square {
  width: 50px;
  height: 50px;
  background-color: #61dafb;
  opacity: 0;
}

更新答案:不需要ref

只需使用以下代码

export default function App() {
  const [ isShown, setShown ] = useState(false)

  return (
    <div>
      <p
        onMouseEnter={() => setShown(true)}
        onMouseLeave={() => setShown(false)}
        style={{ display: "inline-block" }}
        class="paragraph"
      >
        Hover Me
      </p>

      <div className={`square ${isShown ? 'square-full' : ''}`}></div>
    </div>
  );
}

连同我之前提到的额外课程


推荐阅读