javascript - react如何獲取offsetX?
問(wèn)題描述
1.在react中如何獲取元素的offsetX呢?
我的思路是通過(guò)this.state.offsetX獲取,但是this確是null
2.react中可以初始化一個(gè)組件的某些狀態(tài),但是我這樣寫(xiě)getInitialState在控制臺(tái)卻出現(xiàn)了warning錯(cuò)誤。提示如下圖:
具體代碼如下
問(wèn)題解答
回答1:1、es6寫(xiě)法下。初始化默認(rèn)state是在constructor中進(jìn)行
constructor() { super(); this.state = { }}
2、事件回調(diào)函數(shù)中如果要用this,需要手動(dòng)bind
// 方法1this.moveElment.bind(this);// 方法2moveElement = event => {}// 方式3<p onMouseEnter={() => this.moveElement}></p>回答2:
getInitialState 是 ES5 里的寫(xiě)法.在 ES6 里, 應(yīng)該把 state 初始化放到 constructor 里.
class Demo extends Component{ constructor(){super(); // 必須先調(diào)用super, 后面才能用 this this.state = {} }}回答3:
錯(cuò)誤寫(xiě)的很明白, 只有在使用
React.createClass()
的時(shí)候才可以使用getInitialState,在使用ES6的class關(guān)鍵字創(chuàng)建時(shí)使用
this.state = {}
相關(guān)文章:
1. javascript - 關(guān)于apply()與call()的問(wèn)題2. Python中使用超長(zhǎng)的List導(dǎo)致內(nèi)存占用過(guò)大3. java - 在用戶不登錄的情況下,用戶如何添加保存到購(gòu)物車?4. javascript - JS變量被清空5. javascript - axios請(qǐng)求回來(lái)的數(shù)據(jù)組件無(wú)法進(jìn)行綁定渲染6. css3 - 純css實(shí)現(xiàn)點(diǎn)擊特效7. html - eclipse 標(biāo)簽錯(cuò)誤8. 安全性測(cè)試 - nodejs中如何防m(xù)ySQL注入9. javascript - main head .intro-text{width:40%} main head{display:flex}為何無(wú)效?10. javascript - 有適合開(kāi)發(fā)手機(jī)端Html5網(wǎng)頁(yè)小游戲的前端框架嗎?
