简体   繁体   中英

How can I change the css property with styled components onClick?

Hi I´m still new to React okay so I am using styled components for the css stuff for my components and I made the following button:

const SummonButton = styled.button`
    height: 50px;
    border: none;
    outline: none;
    color: #fff;
    background: #111;
    cursor: pointer;
    position: relative;
    z-index: 0;
    border-radius: 10px;
    font-size: 1.5em;

    :before {
        content: '';
        background: linear-gradient(45deg, #ff0000, #ff7300, #fffb00, #48ff00, #00ffd5, #002bff, #7a00ff, #ff00c8, #ff0000);
        position: absolute;
        top: -2px;
        left:-2px;
        background-size: 400%;
        z-index: -1;
        filter: blur(5px);
        width: calc(100% + 4px);
        height: calc(100% + 4px);
        animation: glowing 20s linear infinite;
        opacity: 0;
        transition: opacity .3s ease-in-out;
        border-radius: 10px;
    }

    :active {
        color: #000
    }

    :active:after {
        background: transparent;
    }

    :hover:before {
        opacity: 1;
    }

    :after {
        z-index: -1;
        content: '';
        position: absolute;
        width: 100%;
        height: 100%;
        background: #111;
        left: 0;
        top: 0;
        border-radius: 10px;
    }

    @keyframes glowing {
        0% { background-position: 0 0; }
        50% { background-position: 400% 0; }
        100% { background-position: 0 0; }
    }

But I want this SummonButton to stop after pressing on it ten times, that´s why I made the following line:

 <SummonButton onClick={summonAble < 10 ? SummonAction : {backgroundColor: "red"}}>Summon</SummonButton>

summonAble is a state that counts +1 everytime SummonAction is called. Now after reaching 10 clicks it stops adding so it stays ten, but how can I change now the background color of the button to red after the ten clicks ?

You will have to store somewhere the clicks count.

const [clicks, setClicks] = React.useState(0);

Then you would have to add a prop to the SummonButton to determine if the condition was fulfilled or not:

<SummonButton onClick={...} isRed={clicks > 9} />

const SummonButton = styled.button`
   background: ${({ isRed }) => isRed ? 'red' : 'black'};
   ...
`;

Note : Remember to call the setClicks function with every function call binded to onClick .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM