[英]React - set state of parent component to close modal from a child component
我在父級中設置模態組件的狀態以處理打開和關閉它的過程。 初始顯示狀態為false,在單擊事件中,顯示狀態為true,並出現模式彈出窗口。 這工作正常,問題是我無法將其關閉。 我似乎無法從子級中調用父級組件中的handleHide函數。
class Parent extends Component {
constructor(props) {
super(props);
this.handleHide = this.handleHide.bind(this);
this.state = {
show: false
};
}
handleHide() {
this.setState({ show: false });
}
renderRow() {
return (
<tr>
<td onClick={() => this.setState({ show: true })}>test</td>
<ChildModal show={this.state.show} handleHide={this.handleHide}/>
</tr>
);
}
}
class ChildModal extends Component {
render() {
return (
<Modal onHide={() => this.props.handleHide()} show={this.props.show}>
<Modal.Header closeButton>
<Modal.Title>Test</Modal.Title>
</Modal.Header>
<Modal.Body>
{/* some text */}
</Modal.Body>
</Modal>
);
}
}
您的問題是您要將onHide
傳遞為Modal
組件的道具。 在Modal
,您需要定義onHide
含義
如果您使用reactstrap,請使用以下模態:首先從reactstrap
導入所有內容
<Modal isOpen={this.state.modal} toggle={this.toggle} className={this.props.className}>
<ModalHeader toggle={this.toggle}>Modal
title</ModalHeader>
<ModalBody>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt.
</ModalBody>
<ModalFooter>
<Button color="primary" onClick={this.toggle}>Do Something</Button>{' '}
<Button color="secondary" onClick={this.toggle}>Cancel</Button>
</ModalFooter>
</Modal>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.