样式化的组件:如何在点击时旋转svg图标?

时间:2018-12-02 05:24:04

标签: styled-components

const IconButtonWrapper = styled((props: IconWrapperProps) => {
    return <IconButton {...props} />;
})`
    float: right;
    transform: rotate(0deg);
    overflow: hidden;
    transition: all 0.3s ease-out;
    ${(props) =>
        props.rotate &&
        css`
            transform: rotate(180deg);
        `};
`;

现在,我正在尝试此操作,但它并不完全正确。我目前有props.rotate作为布尔设置,带有单击处理程序,可以在单击时旋转。我该怎么办?

1 个答案:

答案 0 :(得分:0)

从您的示例中尚不清楚如何将“旋转”道具传递给样式化组件,因此我对代码进行了一些重构,并添加了一个容器组件来保持旋转状态: https://codesandbox.io/s/wyx6pqj13w

希望这会有所帮助!

链接中的代码显示在这里

 import React, { Component } from "react";
 import ReactDOM from "react-dom";
 import styled from "styled-components";

 import "./styles.css";

 const IconButton = () => <button>Icon</button>;

 const IconButtonWrapper = styled.div`
   float: right;
   transform: rotate(0deg);
   overflow: hidden;
   transition: all 0.3s ease-out;
   transform: ${props => (props.rotate ? `rotate(180deg)` : "")};
 `;

 class IconButtonContainer extends Component {
   state = {
     rotate: false
   };

   handleClick = () =>
     this.setState(
       prevState => ({ rotate: !prevState.rotate }),
       () => console.log(this.state.rotate)
     );

   render() {
     return (
       <IconButtonWrapper rotate={this.state.rotate} onClick={this.handleClick}>
         <IconButton />
       </IconButtonWrapper>
     );
   }
 }

 function App() {
   return (
     <div className="App">
       <IconButtonContainer />
     </div>
   );
 }

 const rootElement = document.getElementById("root");
 ReactDOM.render(<App />, rootElement);