1. 程式人生 > >React使用ES6語法重構組件代碼

React使用ES6語法重構組件代碼

nat play -s select ets width border extends lstat

首次使用react,要註意react不同版本庫,是ES5還是ES6的寫法,如何做到統一。下面對於ES6語法重構組件的代碼如下:
(1)原始代碼:

<script type="text/babel">
var destination=document.querySelector("#root");
var LightningCounter=React.createClass({
getInitialState:function(){
return {
strickes:0
}
},
timeTricks:function(){
this.setState({
strickes:this.state.strickes+100

});
},
componentDidMount:function(){
setInterval(this.timeTricks,1000)
},
render:function(){
return <h1>{this.state.strickes}</h1>;
}
});
var LightningCounterDisplay=React.createClass({
render:function(){
var distyle={
width:250,
height:250,
textAlign:"center",
backgroundColor:"black",
color:"#CCC",
borderRadius:10,
webkitFilter:"drop-shadow(0px 0px 5px #666)"
};
return <div style={distyle}>
<LightningCounter/>
</div>;
}
});

    ReactDOM.render(
        &lt;LightningCounterDisplay/&gt;,
        destination);
&lt;/script&gt;

(2)重構後的代碼:

<script type="text/babel">

var destination=document.querySelector("#root");

class LightningCounterDisplay extends React.Component{        
        render(){
            var distyle= {
                width:250,
                height:250,
                textAlign:"center",
                backgroundColor:"black",
                color:"#CCC",
                borderRadius:10,
                webkitFilter:"drop-shadow(0px 0px 5px #666)"
            };
            return &lt;div style={distyle}&gt;
            &lt;LightningCounter/&gt;
            &lt;/div&gt;;
        }
}    
class LightningCounter extends React.Component{
            constructor(props){
                super(props);
                this.state={
                    numtricks:0
                }
                this.timeTotalTrick = this.timeTotalTrick.bind(this);  
                //最關鍵的一句是,bind讓實例化的組件任何
                // 地方都能調用該函數,並且函數內部的this指向實例化的組件
            }
            timeTotalTrick(){
                this.setState({
                    numtricks:this.state.numtricks+100
                })
            }
            componentDidMount(){
                setInterval(this.timeTotalTrick,1000)
            }
            render(){
                return &lt;div&gt;{this.state.numtricks}&lt;/div&gt;;
            }
    }

    ReactDOM.render(&lt;LightningCounterDisplay/&gt;,destination);
&lt;/script&gt;

React使用ES6語法重構組件代碼