【问题标题】:animate component entering the DOM in ReactJS在 ReactJS 中动画组件进入 DOM
【发布时间】:2017-07-13 21:59:29
【问题描述】:

刚接触 React,让我很难理解如何在 React 中为元素设置动画。有没有不使用 react-transition-group 的简单方法?假设我有这个代码:

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() 是一种基于 props 呈现一些 div 列表的方法。当 CategoriesList 组件被渲染时,如何使容器 div 动画淡入?

【问题讨论】:

    标签: javascript reactjs animation


    【解决方案1】:

    看看这个

    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 来制作动画。

    【讨论】:

      【解决方案2】:

      您可以使用 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>
            )
         }}
      

      React 生命周期是奇迹发生的地方。 Check out the docs 了解更多信息。还要注意 ref 属性用于访问容器 div 节点的用法。你也可以用它做很多事情,但要确保你只在你的组件被渲染后才尝试这样做。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-01
        • 2018-01-10
        • 1970-01-01
        • 2020-12-01
        • 1970-01-01
        • 2015-10-30
        • 1970-01-01
        相关资源
        最近更新 更多