简体   繁体   中英

ReactJS need to call function from outside class component

I have some various third party code in which I need to be able to call function from outside

//**Import**

import React from 'react'
// .... etc..

//**function I need to have call the function inside react component**

function showDescription(element) {
    // NEED to call function inside component class 
    this.

}

//**Class Component is here and notice state is set, and onClick had bind**

class SectionE extends React.Component {
    constructor(props){
        super(props);
        this.state = {
          visible: false   // setting to true will display the modal dialog box
        }
        this.onClick = this.onClick.bind(this);
    }

//**This is the What I want to call from outside!**     

    onClick() {
        this.setState({visible: true}); // show modal dialog
    }

//**Mount, calling in here works fine**         

    componentDidMount() {

        //this works as another test
        // this.onClick();
    }   

     render()
    {
        return(

//**Testing calling is works fine (Inside )**

    // manually show dialog   this works
   <button type="button" icon="pi pi-external-link" onClick={this.onClick} className="btn btn-primary" id="btnImportant">Add Important People</button>

//**3rd party primereact modal dialog** 

     <Dialog id="modal" header="Important People for ...." visible={this.state.visible} style={{width: '75vw'}} footer={footer} onHide={this.onHide} maximizable>
                    <ImportantFamily/>
     </Dialog>
     )
    }
}

 export default SectionE;

So it is not a child component or parent that i'm trying to call from, but code outside of the class component. Thus I don't see how Ref will even work.

There is a lot more code with SurveyJS 3rd party code that i have outside of react component is biggest reason this code is functions outside.

What are my options?

I think your best option would be to add a prop to your SectionE component and then listen to updates on that prop eg where you are adding SectionE add a prop called "visible" where you can set that visible variable from outside the SectionE class:

<SectionE visible={visible} />

Then do something inside your SectionE when it changes:

// this is inside your SectionE class:
componentDidUpdate(prevProps) {
    if (prevProps.visible !== this.props.visible) {
        this.setState({visible: this.props.visible}); // show/hide modal dialog
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM