[英]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: 这是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/ 工作示例: 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 你不能从另一个组件调用它,因为它的方法属于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>
)
}
}
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 一个非常好的例子和解释可以在这里找到: ReactJS两个组件通信
This is a good approach because it keeps your components decoupled. 这是一种很好的方法,因为它可以使您的组件分离。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.