[英]React: How to close a modal from child opened from parent component
我通過將父狀態作為道具傳遞給子組件來打開子組件模態。 有沒有辦法從子組件本身關閉模態而不受父組件的任何干擾。
class Parent extends Component {
constructor(props) {
super(props);
this.showModal = this.showModal.bind(this);
this.state = {
showModal: false
};
}
showModal() {
this.setState({ showModal: true });
}
renderRow() {
return (
<tr>
<td onClick={() => this.setState({ show: true })}>test</td>
<ChildModal show={this.state.showModal}/>
</tr>
);
}
}
class ChildModal extends Component {
render() {
return (
<Modal show={this.props.showModal}>
<Modal.Header closeButton>
<Modal.Title>Test</Modal.Title>
</Modal.Header>
<Modal.Body>
{/* some text */}
</Modal.Body>
</Modal>
);
}
}
我希望我的孩子模態是獨立的。 這在反應中甚至可能嗎?
您需要將callback as a props
Child component
callback as a props
傳遞, when you click on closeButton in child
Parent Component
when you click on closeButton in child
,它會更新Parent Component
。
// Parent Component
callbackModal = () => {
this.setState({ showModal: false });
}
//ChildButton
closeButtonClickHandler = () => {
this.props.callbackModal();
}
局部狀態變量只能在聲明它的組件內部進行控制。
如果不從父組件傳遞更改傳遞狀態的方法,您將無法從子組件內部關閉模態。
所以為了關閉你的模態,你需要創建一個方法this.closeModal
並將它從父級傳遞給子級......
// Parent
closeModal = () => {
this.setState({showModal: false});
}
// ...
<ChildModal show={this.state.showModal} handleClose={this.closeModal} />
// ...
是的,您可以從子組件關閉它,但是您至少需要父組件的一些干擾,這是因為您已經在父組件中定義了該模型的切換狀態。
只需定義一個方法,該方法將關閉父組件中的模態,將其作為道具傳遞給子組件,並在那里調用它。
//in your parent component
handleModalClose = ()=>{
this.setState({showModal: false})}
現在將它傳遞給您的子組件,然后在類似的事件中調用它
this.props.handleModalClose()
class Parent extends Component {
constructor(props) {
super(props);
this.showModal = this.showModal.bind(this);
this.closeModal = this.closeModal.bind(this)
this.state = {
showModal: false
};
}
showModal() {
this.setState({ showModal: true });
}
closeModal() {
this.setState({ showModal: false });
}
renderRow() {
return (
<tr>
<td onClick={() => this.setState({ show: true })}>test</td>
<ChildModal show={this.state.showModal} close={this.state.closeModal}/>
</tr>
);
}
}
class ChildModal extends Component {
render() {
return (
<Modal show={this.props.showModal}>
<Modal.Header closeButton>
<Modal.Title>Test</Modal.Title>
</Modal.Header>
<Modal.Body>
<buttom onClick={this.props.closeModal()}> ......
</Modal.Body>
</Modal>
);
}
}
當您在父組件中定義狀態時,該狀態周圍的幾乎所有內容都從那里處理。 子組件只能以 props 的形式從父組件接收數據。
父組件控制模態的打開和關閉狀態,以便您能夠從子組件關閉模態,您必須在父組件上定義一個函數closeModal
,該函數將設置showModal
變量(在狀態中定義)你的父組件)從真回到假。
closeModal = () => {
this.setState({ showModal: false });
}
然后將此函數作為道具傳遞給子組件並從那里調用該函數。 當您單擊模態上的關閉按鈕時,狀態將在父組件上更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.