您好,登錄后才能下訂單哦!
首次使用react,要注意react不同版本庫,是ES5還是ES6的寫法,如何做到統(tǒng)一。下面對于ES6語法重構(gòu)組件的代碼如下:
(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 <h2>{this.state.strickes}</h2>;
}
});
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( <LightningCounterDisplay/>, destination); </script>
(2)重構(gòu)后的代碼:
<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 <div style={distyle}> <LightningCounter/> </div>; } } class LightningCounter extends React.Component{ constructor(props){ super(props); this.state={ numtricks:0 } this.timeTotalTrick = this.timeTotalTrick.bind(this); //最關(guān)鍵的一句是,bind讓實(shí)例化的組件任何 // 地方都能調(diào)用該函數(shù),并且函數(shù)內(nèi)部的this指向?qū)嵗慕M件 } timeTotalTrick(){ this.setState({ numtricks:this.state.numtricks+100 }) } componentDidMount(){ setInterval(this.timeTotalTrick,1000) } render(){ return <div>{this.state.numtricks}</div>; } } ReactDOM.render(<LightningCounterDisplay/>,destination); </script>
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。