reactNative中的props和state传值

reactNative中的props和state传值

 

  reactNative项目由不同的组件组成,每个组件都有state和props,

  组件内部传值可以通过state和props传值,外部调用向组件传值需通过

  props进行传值。

 

  案例实现:实现一个动画效果,打开网页,文字从左向右平移200px;

 

      代码实现:

      01.html:

  <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <script src="react.js"></script>
    <script src="react-dom.js"></script>
    <script src="react-with-addons.js"></script>
    <script src="babel.min.js"></script>
    <script type="text/babel" src="01.js"></script>
    <style type="text/css">
    
    </style>
    <title>React</title>
    </head>
    <body>
    </body>
    </html>

 

  01.js:

    let MyComponent=React.createClass({

         //默认熟悉,通过属性配置动画

       getDefaultProps:function(){

         return{

           position:100;//px  平移的距离

             time:10    //ms频率,10ms移动一次

         };

       },

       getIniniaState:function(){

         return {position:0};

       },

       render:function(){

         let style={

            marginLeft:this.state.position

         };

         return <div style={style}>This will animated</div>

       },

 

    });

    //动画执行过程,不断改变状态

    transformComponent:function(){

      if(this.state.position<this.props.position){

        //state改变后重新渲染页面

        this.setState({

          postion:++this.state.position

        });

      }else{

        //完成动画,取消定时器

        clearInterval(this.timer);

      

      }

    }    

 

    //真实的DOM被渲染出来后调用

    componentDidMount:function(){

      if(this.props.position){

        this.timer=setInterval(this.transformComponent,this.props.time);

      }

    }

 

    ReactDOM.render(<MyComponent postion={200} time={5} />,document.body);

 

         

posted @ 2017-03-28 12:25  kerryqpw  阅读(2076)  评论(0编辑  收藏  举报