首页 > 解决方案 > 我可以根据 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;

标签: reactjsstyled-components

解决方案


你不需要参考。您需要将道具传递给UpPartDownPart根据您的状态进行更改。

styled.div的 s 期待props.showUpprops.showDown有时truefalse。所以通过他们isClick boolean

<UpPart showUp={isClick} ></UpPart>
   <Button onClick={handleClick}>HTML</Button>
<DownPart showDown={isClick}></DownPart>

上述更改导致单击按钮时动画运行。但是样式需要更多的工作,因为它会在动画完成后恢复到原始位置。


推荐阅读