简体   繁体   中英

How to call method of React component outside of a class?

I have a modal in my React one page app. I made a class component of modal and render it in some place on the page. I need to call it from many other pages in app this modal. My modal class:

class Modal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      modalShow: false,
    }
  }
  setModalShow(state){
   this.setState({modalShow: state});
  }      
  render(){...}
}

State of modal I keep in modal class. I want to show modal by changing state from outside Modal class. For examle something like

import Modal from './Modal'
...
Modal.setModalShow(true)

But Modal its a class, but I need to call setModalShow in instance of a class. And I don't understand how to do such a thing in React true way.

That kind of behavior requires passing down that function as a child property, Like this:

class Modal extends React.Component {

  constructor(props) {
    super(props);
  }

  setModalShow(state){
   this.props.showModal(true);
  }      

  render(){
    ...
  }
}

And wherever you use the modal, there should be the showing state like:

class ModalWrapper extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      showModal: false
    }
  }

  showModal(state){
    this.setState({modalShow: state});
  }      

  render(){
    return (<Modal showModal={showModal} />);
  }
}

While you can, as other suggests, pass a function that will allow you to register the method to another component, this is probably not the "React" way to open a modal outside of the component (meaning that there are ways that will, I believe, be clearer to write in React than this). I would suggest either making the open state a prop or maintain the modal state in a react context (or even pass the opening function as a context, if more things happen in it than simply opening the modal), which will allow you to avoid prop drilling.

You can read about the context API in the React docs: https://reactjs.org/docs/context.html . Note that it is far simpler to use as a hook in a functional component, but it works fine with classes as well.

you should pass the method setModalShow from Modal to one of its children, and then the child component would call this.props.setModalShow(true) .

I desided to use Redux. In Motivation is described my problem.

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