簡體   English   中英

如何從React中的另一個組件調用組件的方法?

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

我有一個模態組件,有兩個顯示/隱藏模態的方法。 如何從其他組件調用這些方法?

這是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>
    )
  }
}

只要保留對組件的引用,就可以從外部調用組件方法。 例如:

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

如果將對模態的引用傳遞給另一個組件(如按鈕),則會更清晰:

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 );

工作示例: http//jsfiddle.net/69z2wepo/48169/

你不能從另一個組件調用它,因為它的方法屬於RegistrationModal組件,但你可以重構你的代碼,這樣你就可以調用它

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>
    )
  }
}

現在你可以從任何地方打電話,但你需要先輸入它

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

你想要做的是創建一個父組件,它將處理你的模態之間的通信。

一個非常好的例子和解釋可以在這里找到: ReactJS兩個組件通信

這是一種很好的方法,因為它可以使您的組件分離。

暫無
暫無

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

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