我正在我的React应用程序中使用Material UI Modal组件,它将占据屏幕的大部分(大约95%)。因此,我想通过在模式的右上方添加一个小的“ X”图标并允许其关闭,为用户提供一种更直观的关闭模式的方法。我将与[Mod]本身一样的handleClose
函数传递给此图标,但单击该图标时甚至没有调用该函数。我检查了所有道具,并且函数正确传递了下来,只是在CloseIcon组件的onClick上没有得到评估。
Page.js
const Page = props => {
const [open, setOpen] = React.useState(false);
const handleOpen = () => {
setOpen(true);
};
const handleClose = () => {
console.log('testing')
setOpen(false);
};
return (
<>
<Button type="button" onClick={handleOpen} buttonText="Add Meal" />
<ModalContainer
open={open}
handleClose={handleClose}
>
</ModalContainer>
</>
)
};
ModalContainer.js
const ModalContainer = ({
open,
handleClose,
...props
}) => {
return (
<div>
<Modal
open={open}
onClose={handleClose}
>
<StyledDialogContent>
<ModalContent handleClose={handleClose} />
</StyledDialogContent>
</Modal>
</div>
)
};
ModalContent.js
class ModalContent extends React.Component {
render() {
const { handleClose } = this.props;
return (
<Container justify="center" alignItems="center">
<ModalBody flexDirection="column" >
<TopBar justify="flex-end" alignItems="center">
<CloseIcon onClick={handleClose} />
</TopBar>
<BodyContainer>
<FlexContainer>
<RecipeCard />
</FlexContainer>
<FlexContainer>
<MenuCard
title="Custom Food"
icon="https://nutriology-storage.s3.amazonaws.com/Custom-Food.svg"
link=""
/>
</FlexContainer>
</BodyContainer>
</ModalBody>
</Container>
)
}
};
CloseIcon.js
const CloseIcon = props => (
<Circle justify="center" alignItems="center">
<Icon
viewBox="0 0 26 26"
xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
>
<g id="Style-Guide" stroke="none" strokeWidth="1" fillRule="evenodd">
<g
id="Style-Guide---Elements"
transform="translate(-198.000000, -5239.000000)"
strokeWidth="1.5"
>
<g
id="Remove-X-icon-Default"
transform="translate(199.000000, 5240.000000)"
>
<g
id="Group"
transform="translate(12.000000, 12.000000) rotate(-315.000000) translate(-12.000000, -12.000000) translate(6.000000, 6.000000)"
strokeLinecap="round"
>
<path d="M0,6 L12,6" id="Line-2"></path>
<path d="M6,0 L6,12" id="Line-2-Copy"></path>
</g>
</g>
</g>
</g>
</Icon>
</Circle>
);
如何使这个CloseIcon组件实际调用handleClose函数并关闭模式?
编辑:我在这里添加了CloseIcon.js组件以供参考。但是,onClick事件可以正确触发-我通过用一个简单的console.log替换handleClose函数来测试了它,并在单击时适当触发了。
您的CloseIcon
组件无法处理onClick事件。将onClick道具添加到Circle
或Icon
<Circle onClick={props.onClick} justify="center" alignItems="center">
或
<Icon
onClick={props.onClick}
viewBox="0 0 26 26"
xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
>