javascript - 用 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;
}
如果有人可以帮助我,我将不胜感激
解决方案
这是一种不使用的方法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>
);
}
连同我之前提到的额外课程
推荐阅读
- sql-server - Powershell x86:无法加载文件或程序集 Microsoft.SqlServer.BatchParser
- linux - 执行大量渲染任务时如何在 linux 上正确处理屏幕外 EGLContext?
- jquery - Bootstrap 模态显示事件未被任何事件侦听器拦截
- javascript - Nativescript-Vue MobileApp:Axios 返回状态:null 和数据:“”
- xamarin - Xamarin Forms:如何使用 mvvm 动态设置网格中两列的宽度
- css - 如何使引导下拉菜单不改变不同文本的宽度或不影响其他元素?
- asp.net-mvc - ASP.NET MVC 在模型视图中显示数据?
- nlp - 您如何生成 pytorch bert 预训练神经网络的 ONNX 表示?
- node.js - 使用 MarkLogic 节点 API,我可以通过 LDAP 进行身份验证吗?
- excel - vba 粘贴 sheet1 值并保留原始源颜色但不保留字体和其他格式...?