繁体   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