Стилизованное расширение кнопки компонента - PullRequest
0 голосов
/ 28 февраля 2020

Поэтому моя цель - создать компонент базовой кнопки, а затем вариантную кнопку, которая имеет такую ​​же разметку, что и базовая кнопка, но, очевидно, имеет другой стиль, анимацию.

Мой базовый файл - кнопка. js

 import React from 'react';
import styled,{ keyframes, ThemeProvider} from 'styled-components';
import theme from '../../theme/default';

// import {rotatecw, rotateccw} from '../../../theme/keyframes';


const ButtonWrapper = styled.button`
  position: relative;
  color: ${(props) => props.theme.colors.primary};
  width: 256px;
  height: 64px;
  line-height: 64px;
  background: none;
  border: 1px solid ${(props) => props.theme.colors.primary};
    &:hover {
      cursor: pointer;
      color: ${(props) => props.theme.colors.grey};
      border: 1px solid ${(props) => props.theme.colors.grey};
    }
  }

`;

const ButtonText = styled.span`
  // transition: all 0.1s;
  // tranform: scale(1, 1);
`;


function Button(props) {
  return (
    <ThemeProvider theme={theme}>
      <ButtonWrapper>
        <ButtonText>  
          {props.text}
        </ButtonText>
      </ButtonWrapper>
    </ThemeProvider>
  );
}

export default Button;

Пока все хорошо. Мой файл AnimatedButton такой:

    import React from 'react';
import Styled, { keyframes, ThemeProvider} from 'styled-components';
import theme from '../../theme/default';
import Button from '../../components/button/button'

// import {rotatecw, rotateccw} from '../../../theme/keyframes';

const rotatecw = keyframes`
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
`

const rotateccw = keyframes`
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(-360deg);
    }
`



const AnimatedButtonWrapper = Styled(Button)` 
transition: all 0.3s;
  &:before,
  &:after {
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    bottom: 0;
    left: 0;
    z-index: 1;
    transition: all 0.3s;
    border: 1px solid ${(props) => props.theme.colors.primary};
  }
  &:hover {
    cursor: pointer;
    &:after {
      animation-name: ${rotatecw};
      animation-duration: 2s;
    }
    &:before {
      animation-name: ${rotateccw}; 
      animation-duration: 3s;
    }
    &:before,
    &:after {
      left: 96px;
      width: 64px;
      animation-iteration-count: infinite;
      animation-timing-function: linear;
    }
`;

function AnimatedButton(props) {
  return (
    <ThemeProvider theme={theme}>
      <AnimatedButtonWrapper>



      </AnimatedButtonWrapper>
    </ThemeProvider>
  );
}

export default AnimatedButton;

Что меня смутило, так это нижняя часть. кажется повторением ... Как я могу убедиться, что он генерирует ту же разметку, что и кнопка? Я хочу, чтобы моя анимированная кнопка расширяла разметку и css. В конце концов, есть ли способ вызвать мою кнопку таким образом

<Button animatedButton text="test"></Button>

1 Ответ

0 голосов
/ 28 февраля 2020

Когда вы расширяете Button с помощью styled(Button), вы, по сути, создаете более конкретную c его версию и планируете использовать вместо нее новую специфицированную c.

Но когда Вы хотите использовать кнопку как:

<Button animatedButton text="test"></Button>

, которая является вариантом, передающим animatedButton в качестве реквизита, вы хотите включить эти изменения в сам ButtonComponent.

const ButtonWrapper = styled.button`
  All the normal button stuff

  ${props.animated && `
    All the animation stuff goes here
  `}
`
function Button(props) {
  return (
    <ThemeProvider theme={theme}>
      <ButtonWrapper animated={props.animatedButton}>
        <ButtonText>  
          {props.text}
        </ButtonText>
      </ButtonWrapper>
    </ThemeProvider>
  );
}

Если у вас много вариантов как таковых, создание таких стилей может быть мучительным. Вот почему styled-components имеет вспомогательную библиотеку styled-theming, которая может помочь. (Это не очень поможет для части animated, так как это скорее добавление кода, чем изменение.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...