【问题标题】:How can I call a component's method from another component in React?如何从 React 中的另一个组件调用组件的方法?
【发布时间】:2016-11-09 16:32:14
【问题描述】:

我有一个模态组件,它有两种显示/隐藏模态的方法。如何从另一个组件调用这些方法?

这是模态的代码:

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

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

你不能从另一个组件调用它,因为它的一个方法属于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

【讨论】:

  • 执行console.log 似乎可行,但我将如何访问RegistrationModal 类中的registrationModal 参考?
【解决方案2】:

你想要做的是创建一个父组件来处理你的模态之间的通信。

一个非常好的例子和解释可以在这里找到:ReactJS Two components communicating

这是一个很好的方法,因为它使您的组件保持解耦。

【讨论】:

    【解决方案3】:

    只要保留对组件的引用,就可以从外部调用组件方法。例如:

    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/

    【讨论】:

      猜你喜欢
      • 2017-12-09
      • 2022-08-20
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多