![](/img/trans.png)
[英]React Functional Components change state of parent from child without rendering all children
[英]Change parent state from child (where both are functional components)
以下問題的布局如下所示:
.
├── components
│ ├── ModalPolicy.js
│ ├── Footer
│ ├── index.js
├── pages
│ ├── index.js
我試圖在Footer/index.js
上渲染 Modal,但它沒有出現(就像我們在pages/index.js
那樣)。
因此,我想,不僅使我的“antd”模態pages/index.js
也持有模式狀態(開閉VS) 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 缺乏經驗。
如果有更簡單的方法來實現這一點,請告訴我。
謝謝!
問題是您忘記從頁腳組件的道具中解構屬性。 現在,您不是在單擊處理程序上傳遞單個函數,而是傳遞具有該函數的對象。
也就是將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>
)
}
在不解構頁腳組件的參數的情況下,react 接收的props
是具有鍵openModalHandler
的對象
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.