您好,登录后才能下订单哦!
首次使用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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。