您好,登錄后才能下訂單哦!
首次使用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 <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)重構后的代碼:
<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); //最關鍵的一句是,bind讓實例化的組件任何 // 地方都能調用該函數,并且函數內部的this指向實例化的組件 } 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>
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。