简体   繁体   中英

How can I call a component's method from another component in React?

I have a modal component with two methods that show/hide the modal. How can I call those methods from another component?

This is the code for the Modal:

// Dependencies
//==============================================================================
import React from 'react'
import Modal from 'boron/DropModal'

// Class definition
//==============================================================================
export default class RegistrationModal extends React.Component {
  showRegistrationModal() {
    this.refs.registrationModal.show()
  }

  hideRegistrationModal() {
    this.refs.registrationModal.hide()
  }

  render() {
    return (
      <Modal ref="registrationModal" className="modal">
        <h2>Meld je aan</h2>
        <button onClick={this.hideRegistrationModal.bind(this)}>Close</button>
      </Modal>
    )
  }
}

You can call a components method from the outside as long as you keep a reference to the component. For example:

let myRegistrationModal = ReactDOM.render(<RegistrationModal />, approot );
    // now you can call the method:
    myRegistrationModal.showRegistrationModal() 

It's a bit cleaner if you pass a reference to the modal to another component, like a button:

let OpenModalButton = props => (
  <button onClick={ props.modal.showRegistrationModal }>{ props.children }</button>
);
let myRegistrationModal = ReactDOM.render(<RegistrationModal />, modalContainer );

ReactDOM.render(<OpenModalButton modal={ myRegistrationModal }>Click to open</OpenModalButton>, buttonContainer );

Working example: http://jsfiddle.net/69z2wepo/48169/

You cant call it from another component, because its a method belong to RegistrationModal component, but you can refactor your code so you can call it

export function hideRegistrationModal() {
  console.log("ok");
}

export default class RegistrationModal extends React.Component {
  render() {
    return (
      <Modal ref="registrationModal" className="modal">
        <h2>Meld je aan</h2>
        <button onClick={hideRegistrationModal}>Close</button>
      </Modal>
    )
  }
}

now you can call from anywhere but you need to import it first like this

import { RegistrationModal, hideRegistrationModal } from 'path to modal.js'
//       ^-- Component name  ^-- Method

What you want to do is create a parent component which will handle the communication between your modals.

A really great example and explanation can be found here: ReactJS Two components communicating

This is a good approach because it keeps your components decoupled.

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