您的位置:首頁技術文章
文章詳情頁

javascript - react如何獲取offsetX?

瀏覽:154日期:2023-05-17 18:48:09

問題描述

1.在react中如何獲取元素的offsetX呢?

我的思路是通過this.state.offsetX獲取,但是this確是null

2.react中可以初始化一個組件的某些狀態,但是我這樣寫getInitialState在控制臺卻出現了warning錯誤。提示如下圖:

javascript - react如何獲取offsetX?

具體代碼如下javascript - react如何獲取offsetX?

問題解答

回答1:

1、es6寫法下。初始化默認state是在constructor中進行

constructor() { super(); this.state = { }}

2、事件回調函數中如果要用this,需要手動bind

// 方法1this.moveElment.bind(this);// 方法2moveElement = event => {}// 方式3<p onMouseEnter={() => this.moveElement}></p>回答2:

getInitialState 是 ES5 里的寫法.在 ES6 里, 應該把 state 初始化放到 constructor 里.

class Demo extends Component{ constructor(){super(); // 必須先調用super, 后面才能用 this this.state = {} }}回答3:

錯誤寫的很明白, 只有在使用

React.createClass()

的時候才可以使用getInitialState,在使用ES6的class關鍵字創建時使用

this.state = {}

標簽: JavaScript
相關文章:
国产综合久久一区二区三区