繁体   English   中英

如何将 useState 钩子传递给功能组件中的子道具

[英]How to pass useState hook to child props in functional components

我正在尝试使用 useState 钩子来决定模式是否打开。

我在父组件中有这个。

    const handleState = (e) => {
        setModalOpen(e);
    };

    const [ modalOpen, setModalOpen ] = useState(true);

我目前正在按如下方式传递钩子

    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>
    );

在模态中,我得到并使用这样的钩子。

const Modal = ({ img, imgAlt, title, info, functions }) => {
    const [ open, setOpen ] = functions;
<Button
  onClick={() => {
    if (functions.modalOpen) {
        setOpen(false);
    }
  }}

我可以阅读开放罚款。 但我似乎无法调用该函数。

我的想法是,我将根据在元素数组中单击的元素来更改模式上的信息。 可能是通过在元素之间传递更多状态。

我正在考虑可能使用上下文,因为不知何故这感觉变得越来越复杂。

您可以像这样分别传递modalOpenhandleState

<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);
    }
}}

您实际上不需要分别传递modalOpenhandleState 无论如何它应该工作。

另外,你不需要定义一个新的方法来设置 setter 函数。 下面是完全没有必要的。

const handleState = (e) => {
        setModalOpen(e);
    };

https://codesandbox.io/s/pass-usestate-to-child-c0qx6

您遇到的问题是您正在传递一个数组作为functions道具的值,但您试图检查functions.modalOpen就好像它是一个非数组对象一样。 这样你就需要检查functions[0] 您可能想要更改您传入的内容,如下所示:

functions={{ modalOpen, handleState }}

然后你可以像你所做的那样做functions.modalOpen

这就是说,这可能不是解决此问题的正确方法。 modalOpen似乎是一个布尔值,而不是一个函数,在任何情况下,都没有必要将它包装在一个对象中。 Hemanath 的回答提供了一个很好的例子。 .

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM