Call a React component method from outside

前端 未结 11 1579
灰色年华
灰色年华 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:21

    You can do like

    import React from 'react';
    
    class Header extends React.Component{
    
        constructor(){
            super();
            window.helloComponent = this;
        }
    
        alertMessage(){
           console.log("Called from outside");
        }
    
        render(){
    
          return (
          
            Hello
          
          )
        }
    }
    
    export default Header;
    

    Now from outside of this component you can called like this below

    window.helloComponent.alertMessage();
    

提交回复
热议问题