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