简体   繁体   English

如何从每个页面中的导航栏组件的按钮打开模态/对话框反应

[英]How do I open a modal/ dialog from a button from nav bar component in every page react

when I click the icon from the topnav component to open modal ,the modal does not open but "modal open" text is console logged .当我单击 topnav 组件中的图标以打开模态时,模态不会打开,但控制台会记录“模态打开”文本。 The Top nav component has a fixed height in the main page.顶部导航组件在主页中具有固定的高度。 I need to be able to open this modal in every page that's why I added it to Nav-bar .我需要能够在每个页面中打开这个模式,这就是我将它添加到 Nav-bar 的原因。

Topnav component顶部导航组件

export default function Topnav({ page }) {
  const [show, setShow] = useState(false);
  return (
    <nav className="top-nav">
        <icon className='btn' onClick={() => {setShow(!show)}}>
          <VscOrganization size={20} />
        </icon>
      <h4 className="title">{page}</h4>
      
     <Modal show={show}/>
    </nav>
  );
}

modal模态

function Modal({ show }) {
  const classes= useStyles();
  const [open, setOpen] = useState(show);
  const [modalStyle] = useState(getModalStyle);

  return (
    <div>
      <Modal open={open} onClose={() => setOpen(false)}>
        <div style={modalStyle} className={classes.paper + " modal"}>
          <div>
            this is the modal text
            {console.log('modal open')}
          </div>
        </div>
      </Modal>
    </div>
  );
}

Instead of using two states for opening and closing, you need just one in the Topnav component.无需使用两种状态进行打开和关闭,您只需要在Topnav组件中使用一种状态。

Here is what I mean:这就是我的意思:

Topnav component: add onClose to the modal Topnav 组件:将 onClose 添加到模态

export default function Topnav({ page }) {
  const [show, setShow] = useState(false);
  return (
    <nav className="top-nav">
        <icon className='btn' onClick={() => {setShow(true)}}>
          <VscOrganization size={20} />
        </icon>
      <h4 className="title">{page}</h4>
      
     <Modal show={show} onClose={() => setShow(false)}/>
    </nav>
  );
}

modal: remove the open state and just use the props modal:移除open状态,只使用道具

function Modal({ show, onClose }) {
  const classes= useStyles();
  const [modalStyle] = useState(getModalStyle);

  return (
    <div>
      <Modal open={show} onClose={onClose}>
        <div style={modalStyle} className={classes.paper + " modal"}>
          <div>
            this is the modal text
            {console.log('modal open')}
          </div>
        </div>
      </Modal>
    </div>
  );
}

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

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