简体   繁体   中英

How can we open a Popper when page load the first time

With https://material-ui.com/components/popper/ React, material-ui, 在此处输入图像描述 I want to show the Popper just after the page loaded, without clicking on the button.

import React from 'react'
import Popper from '@material-ui/core/Popper'
import Typography from '@material-ui/core/Typography'
import Button from '@material-ui/core/Button'
import Fade from '@material-ui/core/Fade'
import Paper from '@material-ui/core/Paper'

export default function PositionedPopper() {
  const elRef = React.useRef(null)

  return (
    <div>
      <Popper open={true} anchorEl={elRef.current} placement={'left'} transition>
        {({ TransitionProps }) => (
          <Fade {...TransitionProps} timeout={350}>
            <Paper>
              <Typography>The content of the Popper.</Typography>
            </Paper>
          </Fade>
        )}
      </Popper>
      <Button ref={elRef}>left</Button>
    </div>
  )
}

This code shows the popper on the top left on the screen because onInit, anchorEl is Null

How can we set anchorEl when the component loads the first time?

use state instead of ref

export default function App(){
   const [el, setEl] = useState(null);
   const [open, setOpen] = useState(true);
   return (
     <div>
        <button ref={setEl} onClick={()=> setOpen(true)}></button>
        <Popper open={el != null && open} anchorEl={el}>
           ....
        </Popper>
     </div>
   )
}

Init the open status with useEffect would work

const [open, setOpen] = useState(false);
useEffect(() => {
  setOpen(true);
}, []);

<Popper
  open={open}
  ...
/>

Full code:

import React, { useEffect, useState, useRef } from "react";
import Popper from "@material-ui/core/Popper";
import Typography from "@material-ui/core/Typography";
import Button from "@material-ui/core/Button";
import Fade from "@material-ui/core/Fade";
import Paper from "@material-ui/core/Paper";

export default function PositionedPopper() {
  const elRef = useRef(null);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    setOpen(true);
  }, []);
  return (
    <div>
      <Popper
        open={open}
        anchorEl={elRef.current}
        placement={"left"}
        transition
      >
        {({ TransitionProps }) => (
          <Fade {...TransitionProps} timeout={350}>
            <Paper>
              <Typography>The content of the Popper.</Typography>
            </Paper>
          </Fade>
        )}
      </Popper>
      <Button ref={elRef}>left</Button>
    </div>
  );
}

编辑wizardly-banach-46fmm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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