
react-lifecycle.png
start -> getDefaultprops -> getInitialState
componentWillMount :當(dāng)組件即將渲染的時(shí)候觸發(fā)的函數(shù)
componentDidMount:當(dāng)組件渲染完成觸發(fā)的一個(gè)函數(shù)
componentWillUpdate:當(dāng)組件發(fā)生改變的時(shí)候觸發(fā)
componentDidUpdate:當(dāng)組件發(fā)生改變的時(shí)候觸發(fā)
componentWillUnmount:組件被卸載的時(shí)候觸發(fā)
componentWillReceiveProps:props改變之前
shouldComponentUpdate:props改變之后
var HelloReact = React.createClass({
getDefaultprops:function(){
console.log("getDefaultprops");
},
// getInitialState:function(){
// console.log("getInitialState");
// },
componentWillMount:function(){
console.log("componentWillMount");
},
componentDidMount:function(){
console.log("componentDidMount");
},
render:function(){
return(
<div>我是Hello React</div>
)
}
})
ReactDOM.render(<HelloReact />,document.getElementById("root"));
例子;使背景顏色的透明度慢慢變化
// css
<style>
.div{
width:100px;
height: 100px;
background-color: red;
}
</style>
1.state:狀態(tài) 當(dāng)組件自身改變的內(nèi)容,可以使用state處理
1.this.state :獲取
2.this.setState :設(shè)置
2.當(dāng)state改變的時(shí)候,會(huì)觸發(fā)render重新渲染
區(qū)分:props外部組件傳遞的一些值;state組件內(nèi)部改變觸發(fā)的狀態(tài)
//js and HTML
<body>
<div id="root"></div>
<script type="text/babel">
var ComState = React.createClass({
//初始化state
getInitialState:function(){
return{
opacity:1.0
}
},
componentDidMount:function(){
var timer = setInterval(function(){
var opacitys = this.state.opacity;
opacitys-=0.02;
this.setState({
opacity:opacitys
})
}.bind(this),100) //在間隔調(diào)用里this指向window,所以要改變this指向
}, //call-對(duì)象;apply-數(shù)組;bind
componentWillUpdate:function(){
console.log("componentWillUpdate");
},
componentDidUpdate:function(){
console.log("componentDidUpdate");
},
render:function () {
return(
<div className="div" style={{opacity:this.state.opacity}}>{this.props.title}</div>
)
}
})
ReactDOM.render(<ComState title="nihaome" />,document.getElementById("root"));
</script>
</body>