javascript - react如何獲取offsetX?
問題描述
1.在react中如何獲取元素的offsetX呢?
我的思路是通過this.state.offsetX獲取,但是this確是null
2.react中可以初始化一個組件的某些狀態(tài),但是我這樣寫getInitialState在控制臺卻出現(xiàn)了warning錯誤。提示如下圖:
具體代碼如下
問題解答
回答1:1、es6寫法下。初始化默認state是在constructor中進行
constructor() { super(); this.state = { }}
2、事件回調(diào)函數(shù)中如果要用this,需要手動bind
// 方法1this.moveElment.bind(this);// 方法2moveElement = event => {}// 方式3<p onMouseEnter={() => this.moveElement}></p>回答2:
getInitialState 是 ES5 里的寫法.在 ES6 里, 應(yīng)該把 state 初始化放到 constructor 里.
class Demo extends Component{ constructor(){super(); // 必須先調(diào)用super, 后面才能用 this this.state = {} }}回答3:
錯誤寫的很明白, 只有在使用
React.createClass()
的時候才可以使用getInitialState,在使用ES6的class關(guān)鍵字創(chuàng)建時使用
this.state = {}
相關(guān)文章:
1. javascript - 在靜態(tài)頁面上用load 引入的頁面文件問題?2. 代理 - 一個nginx需求,訪問web服務(wù)時,若用戶為測試用戶則轉(zhuǎn)發(fā)到web服務(wù)的測試版本3. javascript - webpack打包后的bundlejs文件代碼不知道什么意思.4. java后臺導(dǎo)出頁面到pdf5. java - instance method中 static后的<K>是什么意思?6. css3 - css如何實現(xiàn)素描描邊效果7. css - 關(guān)于ul的布局8. css - 如何使用 vue transition 實現(xiàn) ios 按鈕一樣的平滑切換效果9. javascript - vue組件通過eventBus通信時,報錯a.$on is not a function10. html - 哪些情況下float會失效?
