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