javascript - 如何将 useState 钩子(Hook)传递给功能组件中的子 Prop

标签 javascript reactjs

我正在尝试使用 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);
    }
  }}

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

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

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

最佳答案

你可以通过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);
    }
}}

关于javascript - 如何将 useState 钩子(Hook)传递给功能组件中的子 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60636099/

相关文章:

javascript - 动态改变AngularJS中静态段落的颜色

javascript - 如何使用 id 显示此模式中的 .php 文件?

javascript - 如何在控制台中隐藏日志消息的来源?

javascript - React 开发服务器无法运行 Apple Macbook pro M1

css - 使最后一个网格单元格处于非事件状态

javascript - React JS - 解析复杂的 Json 结构并填充到下拉列表中

reactjs - 如何将任意字符串 HTML 内容注入(inject)到我的 gatsbyjs 网站的头部?

javascript - 使用 key 时无法获取 d3 选择的更新数据

javascript - 如何在 const 中存储数组

reactjs - 类型错误 : Cannot read property 'isRequired' of undefined