我正在尝试使用 useState Hook 来确定模式是否打开。
我在父组件中有这个。
const handleState = (e) => {
setModalOpen(e);
};
const [ modalOpen, setModalOpen ] = useState(true);
我目前正在按如下方式传递钩子(Hook)
return (
<ListWrapper>
{therapies.map((e, i) => {
return (
<div ref={(e) => (ref.current[i] = e)}>
<CardVertical
title={e.title}
info={e.info}
img={e.img}
imgAlt={e.imgAlt}
functions={[ modalOpen, handleState ]}
/>
</div>
);
})}
<Modal
img={therapies[0].img}
imgAlt={therapies[0].imgAlt}
title={therapies[0].title}
info={therapies[0].info}
functions={[ modalOpen, handleState ]}
/>
</ListWrapper>
);
在模态中,我正在获取并使用这样的钩子(Hook)。
const Modal = ({ img, imgAlt, title, info, functions }) => {
const [ open, setOpen ] = functions;
<Button
onClick={() => {
if (functions.modalOpen) {
setOpen(false);
}
}}
我可以阅读打开罚款。但我似乎无法调用该函数。
我的想法是,我将根据在元素数组中单击的元素来更改模式上的信息。可能通过在元素之间传递更多状态。
我正在考虑使用上下文来代替,因为不知何故这感觉它变得越来越复杂。
最佳答案
你可以通过modalOpen
和 handleState
像这样分开
<Modal
mg={therapies[0].img}
imgAlt={therapies[0].imgAlt}
title={therapies[0].title}
info={therapies[0].info}
isOpen={modalOpen}
toggleModal={handleState}
/>
并在模态组件中使用它作为
const Modal = ({ img, imgAlt, title, info, isOpen, toggleModal }) => {
<Button
onClick={() => {
if (isOpen) {
toggleModal(false);
}
}}
关于javascript - 如何将 useState 钩子(Hook)传递给功能组件中的子 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60636099/