React使用ES6語法重構組件代碼
阿新 • • 發佈:2018-07-08
nat play -s select ets width border extends lstat 首次使用react,要註意react不同版本庫,是ES5還是ES6的寫法,如何做到統一。下面對於ES6語法重構組件的代碼如下:
(1)原始代碼:
(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( <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>
React使用ES6語法重構組件代碼