<html>
<head>
<title>hello world React.js</title>
<script src="build_0.13/react.min.js"></script>
<script src="build_0.13/JSXTransformer.js"></script>
</head>
<body>
<div id="e"></div>
<script type="text/jsx">
var Hello = React.createClass({
getInitialState:function(){
return {opacity:1.0};
},
componentDidMount:function(){
this.timer = setInterval(function(){
var opacity = this.state.opacity;
opacity -= 0.1;
if(opacity < 0.1){
opacity = 1.0
}
this.setState({
opacity:opacity
});
}.bind(this), 100);
},
render:function(){
return (
<div style={{opacity:this.state.opacity}}>
hello {this.props.name}
</div>
);
}
});
//添加組件到e中
React.render(
<Hello name="world" />,
document.getElementById("e")
);
</script>
</body>
</html>
組件的生命周期
組件的生命周期分成三個狀態:
-
Mounting:已插入真實 DOM
-
Updating:正在被重新渲染
-
Unmounting:已移出真實 DOM
React 為每個狀態都提供了兩種處理函數,will 函數在進入狀態之前調用,did 函數在進入狀態之后調用,三種狀態共計五種處理函數。
-
componentWillMount()
-
componentDidMount()
-
componentWillUpdate(object nextProps, object nextState)
-
componentDidUpdate(object prevProps, object prevState)
-
componentWillUnmount()
此外,React 還提供兩種特殊狀態的處理函數。
-
componentWillReceiveProps(object nextProps):已加載組件收到新的參數時調用
-
shouldComponentUpdate(object nextProps, object nextState):組件判斷是否重新渲染時調用
