首頁 > web前端 > js教程 > 主體

淺析TypeScript和React中使用ref的方法

青灯夜游
發布: 2021-02-05 10:01:14
轉載
3212 人瀏覽過

TypeScript與React中如何使用ref?以下這篇文章要跟大家介紹一下ref用法。有一定的參考價值,有需要的朋友可以參考一下,希望對大家有幫助。

淺析TypeScript和React中使用ref的方法

推薦教學:《JavaScript影片教學

父元件

##在父元件中,寫如下:

類別中定義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步,不使用箭頭函數的情況)

this.onRef = this.onRef.bind(this)Copy to clipboardErrorCopied
登入後複製

子元件

在子元件中,寫如下:

1、constructor中onRef綁定this

this.props.onRef(this)Copy to clipboardErrorCopied
登入後複製

#完成以上4步驟,父元件中可以隨便呼叫子元件中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>
        )
    }
}
登入後複製

更多程式相關知識,請造訪:

程式設計影片! !

以上是淺析TypeScript和React中使用ref的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:segmentfault.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!