当使用类扩展作为组件时,React 中的菜单材料 UI 组件不起作用



我正在使用React和material UI来构建一些菜单元素。

如果我使用 react 组件作为function,如果我单击按钮,菜单会按预期显示,但如果我使用class extends Component它不再打开。

import React from 'react';
import {Component } from 'react';
import Button from "@bit/mui-org.material-ui.button";
import Menu from "@bit/mui-org.material-ui.menu";
import MenuItem from "@bit/mui-org.material-ui.menu-item";
import Fade from "@bit/mui-org.material-ui.fade";
class  FadeMenu extends Component {
constructor(props){
super(props)
this.state = {
anchorEl : null,
open: false
}
this.setAnchorEl = this.setAnchorEl.bind(this)
this.handleClick = this.handleClick.bind(this)
this.handleClose = this.handleClose.bind(this)
}
handleClick(event) {
this.setAnchorEl(event.currentTarget);
}
setAnchorEl(value){
this.setState({
anchorEl: value,
open: !this.state.open
})
}
handleClose() {
this.setAnchorEl(null);
}
renderMenu(){
return(
<Menu id="fade-menu" anchorEl={this.state.anchorEl} open={this.state.open} onClose={this.handleClose} TransitionComponent={Fade}>
<MenuItem onClick={this.handleClose}>Profile</MenuItem>
<MenuItem onClick={this.handleClose}>My account</MenuItem>
<MenuItem onClick={this.handleClose}>Logout</MenuItem>
</Menu>
)
}
render(){
return (<div>
<Button aria-owns={this.state.open ? 'fade-menu' : undefined} aria-haspopup="true" onClick={this.handleClick}>
Open with fade transition
</Button>
{this.renderMenu}
</div>)
}
}
export default FadeMenu;

问题是您正在尝试渲染函数,而不是组件:

{this.renderMenu}

调用该函数以从中获取 JSX,它将起作用:

{this.renderMenu()}

最新更新