我浏览了许多有关弹出式锚点的问题,但是在使用材料表库https://github.com/mbrn/material-table中的MaterialTable元素时,我还没有看到任何问题。
在调试时,看起来好像anchorEl正确地保存了按钮引用,但是似乎第二次重新呈现并丢失了引用。据我所知,这是从重新安装的按钮开始的。因此,默认情况下,最终渲染会将弹出框放置在屏幕的左上角。我想知道是否有人找到防止这种重新安装或其他解决方法的方法。
export class UsersList extends Component {
constructor(props) {
super(props);
this.state = {
anchorEl: null,
anchorReference: "anchorEl"
};
}
render() {
const { classes } = this.props;
var { anchorEl } = this.state;
const open = Boolean(anchorEl);
return (
<MaterialTable
isLoading={this.state.isLoading}
columns={[
{ title: "Username", field: "username" },
...more columns
]}
data={this.state.users}
onRowClick={(evt, selectedRow) => this.setState({ selectedRow })}
//where I update my anchorEl on a click on the "edit" icon
actions={[
{
icon: "edit",
tooltip: "Edit",
onClick: (event, rowData) => {
this.setState({ anchorEl: event.currentTarget });
}
},
},
]}
components={{
Body: props => (
<React.Fragment>
<MTableBody {...props} />
<Popover
//a breakpoint here is hit twice. First time with valid ref, second time without ref
getContentAnchorEl={null}
id="myId"
open={open}
onClose={this.handlePopoverClose.bind(this)}
anchorEl={anchorEl}
getContentAnchorEl={null}
anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
transformOrigin={{ vertical: "top", horizontal: "center" }}
open={open}
>
<Typography>The content of the Popover.</Typography>
</Popover>
EDIT **代码和框的运行示例:如果单击“编辑列”行项目,则会在屏幕的左上角而不是行项旁边显示一个弹出窗口:https://codesandbox.io/s/loving-tdd-8r910?file=/src/App.js
答案 0 :(得分:0)
将 popover 移动到单独的组件,以便 anchorEl 与 Popover 位于同一组件中。菜单示例:
function MenuCell() {
const [anchorEl, setAnchorEl] = useState(null);
return (
<div>
<IconButton
aria-label="more"
aria-haspopup="true"
onClick={(event) => setAnchorEl(event.currentTarget)}
>
<MoreVertIcon />
</IconButton>
<Menu
anchorEl={anchorEl}
keepMounted
open={Boolean(anchorEl)}
onClose={() => setAnchorEl(null)}
>
<MenuItem selected={false} onClick={() => setAnchorEl(null)}>
Item 1
</MenuItem>
<MenuItem selected={false} onClick={() => setAnchorEl(null)}>
Item 2
</MenuItem>
<MenuItem selected={false} onClick={() => setAnchorEl(null)}>
Item 3
</MenuItem>
</Menu>
</div>
)
}
并在列单元格定义中使用:
function CustomTable() {
const menuColumn = {
id: 'menus',
Header: '',
Cell: ({ row }) => <MenuCell row={row} />,
};
// ...
}