Call a React component method from outside

前端 未结 11 1570
灰色年华
灰色年华 2020-11-28 04:56

I want to call a method exposed by a React component from the instance of a React Element.

For example, in this jsfiddle. I want to call the alertMessage

11条回答
  •  被撕碎了的回忆
    2020-11-28 05:01

    method 1 using ChildRef:

    public childRef: any = React.createRef();
    
    public onButtonClick= () => {
        console.log(this.childRef.current); // this will have your child reference
    }
    
    
    
    

    Method 2: using window register

    public onButtonClick= () => {
        console.log(window.yourRef); // this will have your child reference
    }
    
     {window.yourRef = ref} }/>`
    
    

提交回复
热议问题