reactjs 页面刷新时模态显示

tyg4sfes  于 2023-02-08  发布在  React
关注(0)|答案(1)|浏览(127)

有一个困难的时间与弄清楚为什么模态显示在页面刷新,但不显示时,关于链接被点击。我认为这是与 prop 传递,但不明白出了什么问题。
App.js文件:

function App() {
  const [showAboutModal, setShowAboutModal] = useState(false);
  const navLinkClicked = (selectedKey) => {
    if (selectedKey==='about') {
      alert(showAboutModal)
      setShowAboutModal(true)
    }
  }

  return (
    <div className="App">
      <AboutModal showAboutModal={showAboutModal}/>

      <Navbar collapseOnSelect expand="lg" bg="light">
      <Container>
        <img width="50" height="50" src={beacon} className="App-logo" alt="logo" />
        <Navbar.Brand href="/">Title</Navbar.Brand>
        <Navbar.Toggle aria-controls="responsive-navbar-nav" />
        <Navbar.Collapse id="responsive-navbar-nav">
          <Nav className="me-auto">  
          </Nav>
          <Nav
            onSelect={(selectedKey) => navLinkClicked(selectedKey)}>
            <Nav.Link eventKey="about">About</Nav.Link>
          </Nav>
        </Navbar.Collapse>
      </Container>
    </Navbar>
    </div>
  );
}

export default App;

关于Modal.js文件:

function AboutModal(showAboutModal) {

  const [showModal, setShowModal] = useState(showAboutModal);

  return (
      <Modal show={showModal}>
        <Modal.Header>
          <Modal.Title>About</Modal.Title>
        </Modal.Header>
        <Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={()=>setShowModal(false)}>
            Close
          </Button>
        </Modal.Footer>
      </Modal>
  );
}

export default AboutModal;

我认为问题出在这条线上:const [showModal, setShowModal] = useState(showAboutModal);

wz3gfoph

wz3gfoph1#

AboutModal组件中showAboutModal的值总是真实的,并计算为{ "showAboutModal": false }这样的对象,这意味着模态在页面加载时可见,因为您使用的是对象来切换可见性,而不是该对象的特定键的值。
AboutModal组件可以在函数声明中解构props,也可以在useState调用中指定键,如下所示:

function AboutModal({ showAboutModal }) { // destructure
  const [showModal, setShowModal] = useState(showAboutModal);
//...

//OR
function AboutModal(props) {
  const [showModal, setShowModal] = useState(props.showAboutModal); // specify key
//...

相关问题