美文网首页
React —— 小Demo

React —— 小Demo

作者: 感觉不错哦 | 来源:发表于2019-02-14 10:08 被阅读50次
单独写了一个之前写过知识点的集合的demo,demo很小,单独拿出来的原因是希望你现在已经可以不用看之前的文章写出这个demo了
    <script type="text/babel">
        class HelloComponent extends React.Component{
            constructor(props){
                super(props);
            }
            render(){
                return(
                  <div>
                  
                  </div>
                )
            }
        }

        ReactDOM.render(<HelloComponent/>,document.getElementById('div'))

    </script>

老规矩,开局初始化

首先说明一下props与state,俩者都是可以通过this读取的,之前也说过props是只读的,如果我们在调用两者的同时此数据要是可变的,那我们要把它声明在state中
写个极其简单的opacity变化例子
    render(){
        return(
           <div>  
              <h1>{this.props.name}</h1>
           </div>
        )
    }
}

ReactDOM.render(<HelloComponent name="React"/>,document.getElementById('div'))

接下来声明一个state数据用来绑定css opacity属性

    constructor(props){
        super(props);
        this.state={opacity:1}
    }

将state绑定元素的style

    render(){
        return(
           <div style={{opacity:this.state.opacity}}>  
              <h1>{this.props.name}</h1>
           </div>
        )
    }

style第一个中括号代表表达式,第二个代表对象

接下来在生命周期函数中控制state的变化,因为我们是操作元素的css所以在componentDidMount生命周期函数,在元素挂载之后,不能之前

    componentDidMount(){
        setInterval(()=>{
            
        }.bind(this),100)
    }

首先我们知道定时器的this指向window 这肯定不行,此时可以利用Function原型下的bind方法绑定this,使其指向React实例

    componentDidMount(){
        setInterval(()=>{
            var opacity=this.state.opacity
            opacity-=.05
            if(opacity<0.1){
                opacity=1
            }
            this.setState({opacity:opacity})
            
        }.bind(this),100)
    }

特意使用相同的opacity变量名是想让大家区分,state中的opacity是字符串,后面的才是变量

class HelloComponent extends React.Component{
    constructor(props){
        super(props);
        this.state={opacity:1}
    }

    componentDidMount(){
        setInterval(()=>{
            var opacity=this.state.opacity
            opacity-=.05
            if(opacity<0.1){
                opacity=1
            }
            this.setState({opacity:opacity})
            
        }.bind(this),100)
    }


    render(){
        return(
           <div style={{opacity:this.state.opacity}}>  
              <h1>{this.props.name}</h1>
           </div>
        )
    }
}

ReactDOM.render(<HelloComponent name="React"/>,document.getElementById('div'))

OK 小demo完成

相关文章

网友评论

      本文标题:React —— 小Demo

      本文链接:https://www.haomeiwen.com/subject/cdpseqtx.html