javascript - react如何獲取offsetX?
問題描述
1.在react中如何獲取元素的offsetX呢?
我的思路是通過this.state.offsetX獲取,但是this確是null
2.react中可以初始化一個組件的某些狀態,但是我這樣寫getInitialState在控制臺卻出現了warning錯誤。提示如下圖:
具體代碼如下
問題解答
回答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 = {}
相關文章:
1. javascript - js中遞歸與for循環同時發生的時候,代碼的執行順序是怎樣的?2. 小程序怎么加外鏈,語句怎么寫!求救新手,開文檔沒發現3. python - linux怎么在每天的凌晨2點執行一次這個log.py文件4. php如何獲取訪問者路由器的mac地址5. android - 鍵盤遮擋RecyclerView6. 如何分別在Windows下用Winform項模板+C#,在MacOSX下用Cocos Application項目模板+Objective-C實現一個制作游戲的空的黑窗口?7. javascript - jQuery each 方法第三個參數args 如何解釋?8. javascript - 在 vue里面用import引入js文件,結果為undefined9. java - new + 類名,一定需要申明一個對象嗎?10. javascript - ...mapGetters和...mapState獲取到的state,怎么拿來在methods中操作?
