reactjs - 我可以根据 onClick 事件切换样式化的组件道具吗?
问题描述
我有两个垂直堆叠的盒子,中间有一个按钮,我想点击按钮,上面的盒子向上移动,底部的盒子向下移动,点击按钮后,它们移动背部。
我使用 useState 挂钩设置布尔数并将其附加到 OnClick 事件 handleClick 函数。现在当你点击按钮时,你可以切换真假。我想用它来打开和关闭我发送到我的样式组件的道具。那可能吗?
我只知道 useRef 钩子可以帮助我获取 DOM 元素,所以当我单击按钮时,我可以获得样式化组件元素,但我不知道如何访问我发送给样式化组件的道具,而且将它附加到我的布尔值。
import React,{ useRef, useState} from "react";
import styled,{css, keyframes} from "styled-components";
const SkillCardContainer = styled.div`
position:relative;
width:300px;
height:450px;
background:blue;
margin:200px auto;
`;
const moveUp = keyframes`
from{ top: 0;}
to{ top: -50%}
`;
const moveDown = keyframes`
from { top: 50;}
to {top: 100%;}
`;
const UpPart = styled.div`
position:absolute;
width:300px;
height:225px;
background:red;
box-sizing:border-box;
top:0
left:0;
z-index:80;
${props => props.showUp ? css`animation: ${moveUp} 1s linear;`:css`animation:none` };
`;
const DownPart = styled.div`
position:absolute;
width:300px;
height:225px;
background:green;
box-sizing:border-box;
top:50%;
left:0;
z-index:80;
${props => props.showDown ? css`animation:${moveDown} 1s linear;`:css`animation:none`};
`;
const Button = styled.button`
width:100px;
height:50px;
box-sizing:border-box;
background:grey;
position:absolute;
top:50%;
left:50%;
transform: translate(-50%, -50%);
z-index:100;
`;
const SkillCard = () => {
const myRef = useRef(null);
const [isClick, setIsClick] = useState(false);
const handleClick = () =>{
setIsClick(!isClick);
};
return (
<React.Fragment>
<SkillCardContainer>
<UpPart showUp ref={myRef} ></UpPart>
<Button onClick={handleClick}>HTML</Button>
<DownPart showDown></DownPart>
</SkillCardContainer>
</React.Fragment>
);
}
export default SkillCard;
解决方案
你不需要参考。您需要将道具传递给UpPart
并DownPart
根据您的状态进行更改。
你styled.div
的 s 期待props.showUp
和props.showDown
有时true
会false
。所以通过他们isClick
boolean
。
<UpPart showUp={isClick} ></UpPart>
<Button onClick={handleClick}>HTML</Button>
<DownPart showDown={isClick}></DownPart>
上述更改导致单击按钮时动画运行。但是样式需要更多的工作,因为它会在动画完成后恢复到原始位置。
推荐阅读
- sql - 在递归查询中对结果进行排序
- laravel - 删除特殊字符和空白字符
- javascript - 如何使用 React 创建具有条件可编辑输入/单元格的表格?
- mysql - 为多语言内容设置数据库的最实用方法是什么?
- azure-web-app-service - 如何将静态资产从 VSTS 部署到多个应用程序?
- java - 有没有办法在所有spring上下文初始化后调用bean中的方法
- javascript - 反应操纵 NumberFormat 格式以有条件地工作
- django - “pip install mysqlclient”需要 microsoft visual c++ 错误
- ios - 使用 CALayer 绘制可动画的激光束
- c# - 跨 UI 和非 UI 线程使用 ObservableCollection