javascript - 从子更改父状态(两者都是功能组件)
问题描述
以下问题的布局如下所示:
.
├── components
│ ├── ModalPolicy.js
│ ├── Footer
│ ├── index.js
├── pages
│ ├── index.js
我试图渲染模态,Footer/index.js
但它没有出现(就像我们所做的pages/index.js
那样)。
因此,我不仅想渲染我的“antd”模态,pages/index.js
而且还保持模态状态(打开与关闭),pages/index.js
同时从一个按钮触发它的“打开”方法,Footer/index.js
因为那是我们的页脚链接已经居住。
障碍是这个问题涉及的所有组件都是功能组件,我在互联网上找到的每个解决方案都解决了父(或两者)是(是)类组件的情况。我想要完成的一般要点如下:
组件/页脚/index.js
// imports..
const Footer = (openModalHandler) => {
return (
<section id="footer">
<Layout>
<div className="content">
<a href="#footer" onclick={openModalHandler}>
Policy
</a>
</div>
</Layout>
</section>
)
}
页面/index.js (next.js)
// imports..
import Footer from '../components/Footer'
import ModalPolicy from '../components/ModalPolicy'
const Index = () => {
const [openPolicy, setOpenPolicy] = React.useState(false)
const closeModalPolicy = () => { /* Called by the Modal itself, don't bother with this */
setOpenPolicy(false)
}
const openModalHandler = () => { /* Called in Footer/index.js */
setOpenPolicy(true)
}
return (
<>
<Some />
<Other />
<Stuff />
<ModalPolicy open={openPolicy} onClose={closeModalPolicy} />
<Footer openModalHandler={openModalHandler}
</>
)
}
组件/ModalPolicy.js
// imports..
import { Modal, Button } from 'antd'
const ModalPolicy = ({ t, open, onClose }) => {
return (
<Modal
title="Política de uso y privacidad"
visible={open}
onCancel={onClose}
footer={null}
width="fit-content">
dangerouslySetInnerHTML={{
__html:
`<h1>I'd really like to use dangerouslySetInnerHTML here</h1>
<h2>It would make things a lot easier (assuming it won't look like crap on the browser)</h2>
`
}}
</Modal>
)
}
注意:我不太确定我是否真的必须在 pages/index.js 上渲染 Modal 才能正确显示。实际上,我对 React(因为我是后端开发人员)和浏览器端的 JavaScript 非常缺乏经验。
如果有更简单的方法可以做到这一点,请告诉我。
谢谢!
解决方案
问题是您忘记从 Footer 组件的 props 中解构属性。现在,您不是通过单击处理程序传递单个函数,而是传递具有该函数的对象。
又名更改const Footer = (openModalHandler)
为const Footer = ({openModalHandler})
const Footer = ({openModalHandler}) => {
----------------^----------------^ // curly brackets to desturcture
return (
<section id="footer">
<Layout>
<div className="content">
<a href="#footer" onClick={openModalHandler}>
------------------------------^------ // capitalize the c (camelCase properties)
Policy
</a>
</div>
</Layout>
</section>
)
}
在不解构页脚组件的参数的情况下props
,react 接收到的参数是带有键的对象openModalHandler
推荐阅读
- c# - 在这种情况下,我应该在 CreateDC 之后使用 DeleteDC
- reactjs - 从 Nginx 提供 Spring REST API,CORS 和 CSRF 的问题
- unity3d - 如何在 Unity 中对 Playstation 平台进行区域检查?
- forms - 默认选中单选按钮(未映射的 ChoiceType 字段)
- web-services - 修改底层 Web 服务签名后如何回收 ColdFusion Web 服务
- agile - SCRUM - 敏捷开发 - 一名开发人员同时处理多个用户故事
- mysql - 主键创建失败后查找重复行
- laravel - 上传图片问题
- google-cloud-platform - 我可以从同一个 windows 2012 服务器同时使用多个 gcloud 帐户吗?
- mysql - RDS InnoDB RAM 使用问题