标签:stat trick splay mount ali reac state es6 set
首次使用react,要注意react不同版本库,是ES5还是ES6的写法,如何做到统一。下面对于ES6语法重构组件的代码如下:<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>
标签:stat trick splay mount ali reac state es6 set
原文地址:http://blog.51cto.com/13238147/2138824