首页 > 解决方案 > 从子更改父状态(两者都是功能组件)

问题描述

以下问题的布局如下所示:

.
├── 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 非常缺乏经验。

如果有更简单的方法可以做到这一点,请告诉我。

谢谢!

标签: javascriptreactjsnext.jsreact-functional-component

解决方案


问题是您忘记从 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

如果您愿意,可以现场玩 :)


推荐阅读