React Class 如何锚定弹出框 [英] React Class how to AnchorEl Popover

查看:58
本文介绍了React Class 如何锚定弹出框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 React 和 Hooks 的新手,比如 useState.我很难理解这个概念以及如何使用它.所以我不想制作比我更复杂的作品和文件.

Hi I'm new to React and Hooks like useState. I'm having a hard time grasping the concept and how to use it. So I don't want to make more complex pieces and files than I have too.

我在将 React.component 从函数切换到类时遇到问题,Popover.

I've run into a problem switching a React.component from a function to a class, Popover.

我已经创建了一个 CodeSandbox 来尝试展示我也想切换的内容.但是,我只是无法很好地理解文档以使其发生.

I've forked off a CodeSandbox to try to show what I'd like to switch too. But, I just can't understand the documentation well enough to make it happen.

让 React.Class.Component 使用 React-States 需要做什么?

What needs to happen to have a React.Class.Component use React-States?

推荐答案

    import React, { Component } from "react";
import { makeStyles } from "@material-ui/core/styles";
import Popover from "@material-ui/core/Popover";
import Typography from "@material-ui/core/Typography";
import Button from "@material-ui/core/Button";

// const useStyles = makeStyles(theme => ({
//   typography: {
//     padding: theme.spacing(2)
//   }
// }));

export default class SimplePopover extends Component {
  constructor(props) {
    super(props);
    // const classes = useStyles();
    // const [anchorEl, setAnchorEl] = React.useState(null);
    this.state = {
      anchorEl: null,
      open: false,
      id: undefined
    }
    this.handleClick = this.handleClick.bind(this);
    this.handleClose = this.handleClose.bind(this);

    // const open = Boolean(anchorEl);
    // const id = open ? "simple-popover" : undefined;
  }

  handleClick(event) {
    this.setState({anchorEl: event.currentTarget, open: Boolean(event.currentTarget), id: "simple-popover"});
  }

  handleClose(event) {
    this.setState({anchorEl: event.currentTarget, open: false, id: undefined});
  }

  render() {
    return (
      <div>
        <Button
          aria-describedby={this.id}
          variant="contained"
          color="primary"
          onClick={this.handleClick}
        >
          Open Popover
        </Button>
        <Popover
          id={this.id}
          open={this.state.open}
          anchorEl={this.state.anchorEl}
          onClose={this.handleClose}
          anchorOrigin={{
            vertical: "bottom",
            horizontal: "center"
          }}
          transformOrigin={{
            vertical: "top",
            horizontal: "center"
          }}
        >
          {/* <Typography className={this.classes.typography}> */}
          <div>The content of the Popover.</div>
          {/* </Typography> */}
        </Popover>
      </div>
    );
  }
}

);}}

<块引用>

错误

const [anchorEl, setAnchorEl] = React.useState(null);

不能在类组件中使用 Hook

You cannot use a Hook inside a class Component

这篇关于React Class 如何锚定弹出框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆