2017-03-08 76 views
3

我使用styled-components而不是传统的CSS方式。但我不知道它如何与ReactCSSTransitionGroup一起工作。使用ReactCSSTransitionGroup与样式组件

基本上,ReactCSSTransitionGroup在css资源中查找某些类名,然后在整个生命周期中应用到一个组件。但是,由于styled-components没有任何类名,所以样式直接应用于组件。

我知道我可以选择不使用ReactCSSTransitionGroup,因为两种技术看起来不兼容。但是,当我仅使用styled-components时,看起来我无法在组件卸载时呈现任何动画 - 它是纯CSS,无法访问组件的生命周期。

任何帮助或建议表示赞赏。

回答

-1

在CSS中试试camelCase,如下所示。

.enter { 

} 
.enterActive { } 
2

使用您的阵营程序是自举injectGlobal()风格组分的辅助方法。使用这种方法,您可以设置任何CSS选择器的样式,就好像您使用传统的CSS一样。

首先创建一个JS文件导出文本与CSS的react-transition-group模板(请不是我使用V2.1新的类名语法):上然后

globalCss.js

const globalCss = ` 
    .transition-classes { 
     /* The double class name is to add more specifity */ 
     /* so that this CSS has preference over the component one. */ 
     /* Try removing it, you may not need it if properties don't collide */ 
     /* https://www.styled-components.com/docs/advanced#issues-with-specificity */ 

     &-enter&-enter { 
     } 

     &-enter&-enter-active { 
     } 

     &-exit&-exit { 
     } 

     &-exit&-exit-active { 
     } 
    } 
`; 

export default globalCss; 

您入口点文件:

index.jsx

import { injectGlobal } from "styled-components"; 
import globalCss from "./globalCss.js"; 

injectGlobal`${ globalCss }`; // <-- This will do the trick 

ReactDOM.render(
    <Provider store={ Store } > 
     <HashRouter > 
      <Route path="/" component={ Component1 } /> 
      <Route path="/" component={ Component2 } /> 
     </HashRouter> 
    </Provider>, 
    document.getElementsByClassName("react-app")[0] 
); 

但是,即使使用样式化组件,如果您只是使用CSS/SASS/Less编写react-trasition-group的类,它也可以很好地工作。

0

您可以在样式组件中使用css变量选择器。就像这样:

const Animation = styled(ReactCSSTransitionGroup)` 
 
    ${({ transitionName }) => `.${transitionName}-enter`} { 
 
    opacity: 0; 
 
    } 
 

 
    ${({transitionName}) => `.${transitionName}-leave`} { 
 
    opacity: 1; 
 
    } 
 
` 
 

 
const animationID = 'some-hashed-text' 
 

 
const AnimationComponent = props => (
 
    <Animation 
 
    transitionName={animationID} 
 
    transitionEnterTimeout={0.1} 
 
    transitionLeaveTimeout={2000} 
 
    > 
 
    <div>some content</div> 
 
    </Animation> 
 
)