這篇文章給大家分享的是有關(guān)TypeScript和React如何使用ref的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
在父組件中,編寫如下:
類中定義child,用于存放子組件的作用域
public child: any;Copy to clipboardErrorCopied
綁定子組件作用域
public onRef(ref:any){ this.child = ref }Copy to clipboardErrorCopied
子組件上綁定ref
<ChildPage onRef={(el)=>this.onRef(el)} />Copy to clipboardErrorCopied
onRef 綁定this(第3步,不使用箭頭函數(shù)的情況)
this.onRef = this.onRef.bind(this)Copy to clipboardErrorCopied
在子組件中,編寫如下:
1、constructor中onRef綁定this
this.props.onRef(this)Copy to clipboardErrorCopied
完成以上4步驟,父組件中可以隨便調(diào)用子組件中state的值以及方法。
export class ParentCom extends React.Component<{}, {}> { constructor(props:{}){ super(props); this.onRef = this.onRef.bind(this); } public child: any; onRef(ref:any){ this.child = ref; } getChildFun(){ this.child.testFun(); } render(){ return ( <div> <span>父組件</span> <ChildCom onRef={this.onRef}></ChildCom> </div> ) } } interface childProps{ onRef? : any } export class ChildCom extends React.Component<childProps, {}> { constructor(props:{}){ super(props); this.props.onRef(this); } testFun(){ console.log(123) } render(){ return ( <div> <span>子組件</span> </div> ) } }
感謝各位的閱讀!關(guān)于“TypeScript和React如何使用ref”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
新聞標(biāo)題:TypeScript和React如何使用ref-創(chuàng)新互聯(lián)
地址分享:http://vcdvsql.cn/article44/ddgdhe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供全網(wǎng)營銷推廣、網(wǎng)站導(dǎo)航、外貿(mào)建站、微信小程序、網(wǎng)站策劃、ChatGPT
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容