Call a React component method from outside

前端 未结 11 1466
灰色年华
灰色年华 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:19
    class AppProvider extends Component {
      constructor() {
        super();
    
        window.alertMessage = this.alertMessage.bind(this);
      }
    
      alertMessage() {
        console.log('Hello World');
     }
    }
    

    You can call this method from the window by using window.alertMessage().

    0 讨论(0)
  • 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 (
          <AppBar style={{background:'#000'}}>
            Hello
          </AppBar>
          )
        }
    }
    
    export default Header;
    

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

    window.helloComponent.alertMessage();
    
    0 讨论(0)
  • 2020-11-28 05:23

    I use this helper method to render components and return an component instance. Methods can be called on that instance.

    static async renderComponentAt(componentClass, props, parentElementId){
             let componentId = props.id;
            if(!componentId){
                throw Error('Component has no id property. Please include id:"...xyz..." to component properties.');
            }
    
            let parentElement = document.getElementById(parentElementId);
    
            return await new Promise((resolve, reject) => {
                props.ref = (component)=>{
                    resolve(component);
                };
                let element = React.createElement(componentClass, props, null);
                ReactDOM.render(element, parentElement);
            });
        }
    
    0 讨论(0)
  • 2020-11-28 05:24

    With React hook - useRef

    
    
    const MyComponent = ({myRef}) => {
      const handleClick = () => alert('hello world')
      myRef.current.handleClick = handleClick
      return (<button onClick={handleClick}>Original Button</button>)
    }
    
    MyComponent.defaultProps = {
      myRef: {current: {}}
    }
    
    const MyParentComponent = () => {
      const myRef = React.useRef({})
      return (
        <>
          <MyComponent 
            myRef={myRef}
          />
          <button onClick={myRef.current.handleClick}>
            Additional Button
          </button>
        </>
      )
    }
    

    Good Luck...

    0 讨论(0)
  • 2020-11-28 05:24

    It appears statics are deprecated, and the other methods of exposing some functions with render seem convoluted. Meanwhile, this Stack Overflow answer about debugging React, while seeming hack-y, did the job for me.

    0 讨论(0)
提交回复
热议问题