<!-- 準(zhǔn)備好一個(gè)容器 --> <div id="test"></div> <!-- 引入核心庫(kù) React對(duì)象 --> <script src="../js/react.development.js"></script> <!-- 引入react-dom, 用于支持react操作dom --> <script src="../js/react-dom.development.js"></script> <!-- 引入babel, 用于將jxs轉(zhuǎn)為js --> <script src="../js/babel.min.js"></script> <script type="text/babel"> //1. 創(chuàng)建類式組件 class Weather extends React.Component{ //初始化狀態(tài) state = {isHot:true} render() { const {isHot} = this.state return <h1 id="title" onClick={this.changeWeather}>今天天氣很{isHot ? "炎熱":"涼爽"}</h1> } //自定義方法: 要用賦值語句的形式 + 箭頭函數(shù) changeWeather = ()=>{ console.log(this); //箭頭函數(shù)沒有自己的this, 它會(huì)找外側(cè)函數(shù)的this做為箭頭函數(shù)自己的this let isHost = this.state.isHot; //注意: 狀態(tài)(state)不可以直接更改(React不認(rèn)), 要借助一個(gè)內(nèi)置的API setState 如下: this.setState({isHot:!isHost}) } } ReactDOM.render(<Weather/>,document.getElementById("test")) </script>
State應(yīng)用總結(jié):
1> state 是組件對(duì)象最重要的屬性,值是對(duì)象(可以包含多個(gè)key-value的組合)
2> 組件被稱為"狀態(tài)機(jī)", 通過更新組件的state來更新對(duì)應(yīng)的頁(yè)面顯示(重新渲染組件)
注意:
1. 組件中render方法中的this為組件實(shí)例對(duì)象
2. 組件中自定義的方法中 this 為undefined?如何解決?
a. 強(qiáng)制綁定 this, 通過函數(shù)對(duì)象的bind();
b. 賦值 + 箭頭函數(shù)
3. 狀態(tài)數(shù)據(jù): 不能直接修改或者更新,通過setState方法
當(dāng)更新State屬性值時(shí),render會(huì)再次渲染
以下為非簡(jiǎn)化用法,需要在類中的constructor方法中為每一個(gè)方法重新綁定this(類中的方法存儲(chǔ)在原型對(duì)象上,事件綁定是這個(gè)方法,里面的this為undefined)
//1. 創(chuàng)建類式組件 class Weather extends React.Component{ constructor(props){ super(props); this.state = {isHot:true} this.changeWeather = this.changeWeather.bind(this); //改變this.changeWeather函數(shù)的this為當(dāng)前實(shí)例對(duì)象 } //render調(diào)用幾次? 1 + n 次 1是初始化的那次,n是每次更新狀態(tài)時(shí)的值 render() { const {isHot} = this.state return <h1 id="title" onClick={this.changeWeather}>今天天氣很{isHot ? "炎熱":"涼爽"}</h1> //注意:{clickTitle} -- 渲染時(shí)返回一個(gè)方法 不是 {clickTitle() -- 渲染時(shí)會(huì)執(zhí)行函數(shù), 返回undefined} //onClick : 不是onclick } changeWeather(){ //changeWeather放在哪里?---Weather的原型對(duì)象上, 供實(shí)例使用 //由于changerWeather是作為onClick的回調(diào)(通過this找到,非直接調(diào)用); 所以不是通過實(shí)例調(diào)用的, 是直接調(diào)用 //類中的方法默認(rèn)開啟了局部的嚴(yán)格模式, 所以changeWeather中的this為undefined; //console.log(this); //undefined // console.log("標(biāo)題被單擊了"); let isHost = this.state.isHot; // this.state.isHot = !this.state.isHot; //直接更改 //console.log(this.state.isHot); //嚴(yán)重注意: 狀態(tài)(state)不可以直接更改(React不認(rèn)), 要借助一個(gè)內(nèi)置的API setState 如下: this.setState({isHot:!isHost}) } } ReactDOM.render(<Weather/>,document.getElementById("test"))