2017-03-08 41 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> 
 
)