簡體   English   中英

ReactJS 需要從 class 組件外部調用 function

[英]ReactJS need to call function from outside class component

我有一些不同的第三方代碼,我需要能夠從外部調用 function

//**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;

所以它不是我試圖調用的子組件或父組件,而是 class 組件之外的代碼。 因此,我看不到Ref甚至會如何工作。

我在 React 組件之外擁有的 SurveyJS 3rd 方代碼還有更多代碼,這是該代碼在外部起作用的最大原因。

我有哪些選擇?

我認為您最好的選擇是向您的SectionE組件添加一個道具,然后收聽該道具的更新,例如在您添加SectionE的位置添加一個名為“可見”的道具,您可以在其中從 SectionE class 外部設置該可見變量:

<SectionE visible={visible} />

然后在 SectionE 發生變化時做一些事情:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM