React之函数中的this指向
? ? ? ?我們都知道在React中使用函數(shù)時(shí),有兩種寫法,一是回調(diào)函數(shù),二是直接調(diào)用,但需要在構(gòu)造函數(shù)中綁定this,只有這樣,函數(shù)中的this才指向本組件
? ? ? ?總結(jié)一下沒有綁定this的函數(shù)中的this指向
? ? ? ? 不管是在本組件的元素上調(diào)用的函數(shù)還是傳遞給子組件的函數(shù),不管有沒有綁定this,它們調(diào)用的都是本組件里的函數(shù),即調(diào)用函數(shù)的this指向的是本組件
? ? ? ? ?例如: class Parent extends React.Component {
? ? ? ? ? ? constructor(props) { supper(props); }
? ? ? ? ? ? ?handleSubmit() {}
? ? ? ? ? ? ? render() {
? ? ? ? ? ? ? ? ? return (
? ? ? ? ? ? ? ? ? ? ?<div>
? ? ? ? ? ? ? ? ? ? ? ? ?<button onClick={this.handleSubmit}>點(diǎn)擊按鈕</button>
? ? ? ? ? ? ? ? ? ? ? ? ?<Child? onFunc={this.handleSubmit} />
? ? ? ? ? ? ? ? ? ? ?</div>
? ? ? ? ? ? ? ? ? );
? ? ? ? ? ? ? }
? ? ? ? ?}
? ? ? ? <button>與<Child />調(diào)用的都是Parent組件中的handleSubmit,不同的是handleSubmit函數(shù)中的this指向
? ? ? ? <button>的handleSubmit中的this為undefined
? ? ? ? <Child />的handleSubmit中的this指向Child組件的propTypes對(duì)象
?
更多專業(yè)前端知識(shí),請(qǐng)上 【猿2048】www.mk2048.com
總結(jié)
以上是生活随笔為你收集整理的React之函数中的this指向的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 获取当前鼠标的位置以及组件的位置
- 下一篇: react-性能优化