javascript - 如何在页面第一次加载时打开 Popper

标签 javascript reactjs material-ui ref popper.js

https://material-ui.com/components/popper/ react , Material 用户界面, enter image description here 我想在页面加载后立即显示 Popper,而不单击按钮。

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>
  )
}

此代码在屏幕左上角显示弹出窗口,因为 onInit、anchorEl 为 Null

组件第一次加载时如何设置anchorEl

最佳答案

使用useEffect初始化打开状态可以工作

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

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

完整代码:

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>
  );
}

Edit wizardly-banach-46fmm

关于javascript - 如何在页面第一次加载时打开 Popper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61003829/

相关文章:

javascript - 如何在javascript中的每次迭代中以随机间隔运行setTimeout()?

javascript - 使用 ReactJS 获取数据不显示在浏览器上

reactjs - 如何在加载 React 页面时滚动它?

css - Material UI - 选择下划线颜色

reactjs - Material 用户界面 : Place the avatar and text next to each other in the first column of the table

javascript - javascript 中的函数标识

javascript - Javascript中给定字符之间的字符串子串集

material-ui - 如何将mailto与 Material ui一起使用?

javascript - Node.js 集群尽可能频繁地处理数据

html - 瞬间显示损坏的图像标签