反应类如何锚定弹出框



嗨,我是 React 和 Hooks 的新手,比如 useState。我很难掌握这个概念以及如何使用它。 所以我不想制作比我更复杂的片段和文件。

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

我已经分叉了一个CodeSandbox,试图展示我也想切换什么。 但是,我只是无法很好地理解文档以实现它。

让 React.Class.Component 使用 React-State 需要发生什么?

<Button aria-describedby={id} variant="contained" onClick={handleClick}>
Open Popover
</Button>
<Popover
id={id}
open={open}
anchorEl={anchorEl}
onClose={handleClose}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'left',
}}
>
<Typography sx={{ p: 2 }}>The content of the Popover.</Typography>
</Popover>
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);

您不能在类组件中使用钩

相关内容

  • 没有找到相关文章

最新更新