本文介绍了如何从父组件打开Material UI Modal?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的父组件:
import React from 'react';
import ChildModal from 'ChildModal';
const ParentComponent = () => (
<div>
<span>Click </span>
<a>HERE TO OPEN MODAL</a>
<div>
);
这是我的孩子部分:
import React, { useState } from "react";
import { Modal, Backdrop, Fade } from "@material-ui/core";
const ChildModal = () => {
const [open, setOpen] = useState(false);
const handleOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
return (
<div>
<button type="button" onClick={handleOpen}>
react-transition-group
</button>
<Modal
aria-labelledby="transition-modal-title"
aria-describedby="transition-modal-description"
className="modal"
open={open}
onClose={handleClose}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500
}}
>
<Fade in={open}>
<div className="paper">
<h2 id="transition-modal-title">Transition modal</h2>
<p id="transition-modal-description">
react-transition-group animates me.
</p>
</div>
</Fade>
</Modal>
</div>
);
};
因此,基本上,如何从父组件打开模式?我应该通过道具还是以其他方式处理 open
状态?
So, basically, how can I open modal from parent component?Should I pass a prop or handle open
state in some other matter?
还可以使用 a
标签完成此操作吗?我需要使用它来保持一致,这不是实际情况,但您会明白这一点.:)
Also, can this be done with a
tag? I need to use it to keep it in the same line, and this is not real-world scenario, but you'll get the point. :)
谢谢.
推荐答案
import React from 'react';
import ChildModal from 'ChildModal';
const ParentComponent = () => (
const [open, setOpen] = useState(false);
const handleOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
return (
<div>
<input type="button" onClick={handleOpen}>CLICK HERE TO OPEN MODAL</input>
<ChildModal open={open} onClose={handleClose}
<div>
);
在Modal中设置像这样的props属性以设置open和handleClose:
In Modal set props attributes like this to set open and handleClose :
<Modal
aria-labelledby="transition-modal-title"
aria-describedby="transition-modal-description"
className="modal"
{...props}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500
}}
>
<Fade in={this.props.modalState}>
<div className="paper">
<h2 id="transition-modal-title">Transition modal</h2>
<p id="transition-modal-description">
react-transition-group animates me.
</p>
</div>
</Fade>
</Modal>
这篇关于如何从父组件打开Material UI Modal?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!