2017-07-13 69 views
0

對React來說是新的,這讓我很難理解如何在React中動畫元素。有沒有簡單的方法來做到這一點,而不使用react-transition-group?假設我有這樣的代碼:動畫組件進入ReactJS中的DOM

class CategoriesList extends Component{ 
    renderList(){ 
    return this.props.categories.map((category) => { 
     return(
     <div 
      key={category.title} 
      className="button"> 
      {category.title} 
     </div> 
     ) 
    }) 
    }    
    render(){ 
    return (
     <div className= 'container'> 
     {this.renderList()} 
     </div> 
    ) 
    }} 

其中renderList()是一種方法,它根據道具呈現一些div的列表。如何在生成CategoriesList組件時將容器div淡入淡出?

回答

0

檢查了這一點

class Example extends React.Component { 
 
    componentDidMount() { 
 
    
 
    dynamics.animate(this.refs.a, { 
 
     translateX: 150, 
 
     opacity: 1 
 
    }, { 
 
     type: dynamics.spring, 
 
     frequency: 200, 
 
     friction: 200, 
 
     duration: 1500 
 
    }) 
 
    } 
 

 
    render() { 
 
    return (
 
     <div ref="a" style={{ 
 
     padding: 10, 
 
     background: 'tomato', 
 
     color: 'white', 
 
     width: 200, 
 
     fontFamily: 'Helvetica' 
 
     }}> 
 
     Animating Div 
 
     </div> 
 
    ) 
 
    } 
 
} 
 

 

 

 
ReactDOM.render(<Example />, document.querySelector('#root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/dynamics.js/1.1.5/dynamics.min.js"></script> 
 

 
<div id="root"></div>

我用dynamics.js這裏動畫。

0

您可以使用React生命週期和基本CSS輕鬆完成此操作。

CSS:

.container { 
    opacity: 0; 
    transition: 200ms opacity ease-in-out; 
} 

陣營:

class CategoriesList extends Component{ 
    ... 
    componentDidMount() { 
    this.refs.container.style.opacity = 1; 
    } 
    ... 
    render(){ 
    return (
     <div className= 'container' ref="container"> 
     {this.renderList()} 
     </div> 
    ) 
    }} 

的陣營生命週期是神奇在哪裏發生。 Check out the docs瞭解更多信息。還要注意使用ref屬性來訪問容器div節點。你也可以做很多事情,但是確保你只在你的組件被渲染後才嘗試這個。