TypeScript與React中如何使用ref

父組件

在父組件中,編寫以下:函數

  1. 類中定義child,用於存放子組件的做用域this

    public child: any;Copy to clipboardErrorCopied
  2. 綁定子組件做用域spa

    public onRef(ref:any){
     this.child = ref
    }Copy to clipboardErrorCopied
  3. 子組件上綁定refcode

    <ChildPage onRef={(el)=>this.onRef(el)} />Copy to clipboardErrorCopied
  4. onRef 綁定this(第3步,不使用箭頭函數的狀況)
this.onRef = this.onRef.bind(this)Copy to clipboardErrorCopied

子組件

在子組件中,編寫以下:ip

  1. constructor中onRef綁定this作用域

    this.props.onRef(this)Copy to clipboardErrorCopied

完成以上4步驟,父組件中能夠隨便調用子組件中state的值以及方法。get

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>
        )
    }
}
相關文章
相關標籤/搜索