ReactJS需要从外部类组件调用函数

我有一些第三方代码,需要能够从外部调用函数

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

因此我不是要尝试调用的子组件或父组件,而是类组件之外的代码。因此,我什至看不到Ref将如何工作。

SurveyJS 3rd第三方代码中有很多代码,而我在react组件之外是最大的原因,因为该代码是外部函数。

我有什么选择?

cjz7366 回答:ReactJS需要从外部类组件调用函数

我认为您最好的选择是在SectionE组件中添加一个道具,然后收听该道具的更新,例如在添加SectionE的位置添加一个名为“ visible”的道具,您可以在SectionE类外部设置该可见变量:

<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
    }
}
本文链接:https://www.f2er.com/3140997.html

大家都在问