我正在使用Material UI popper,但是anchorEl的状态为null。 Material UI包含一个示例,其中包含有关如何使用Popper的功能组件。我正在使用基于类的组件,但逻辑类似。请帮助我找到缺失或出问题的地方。
export class Toolbar extends PureComponent<IToolbarProps, IToolbarState> {
constructor(props) {
super(props);
this.state = {
anchorEl: null,
open: false,
};
flipOpen = () => this.setState({ ...this.state, open: !this.state.open });
handlePopper = (event: React.MouseEvent<HTMLElement>) => {
this.state.anchorEl
? this.setState({ anchorEl: null })
: this.setState({ anchorEl: event.currentTarget });
this.flipOpen();
};
render(){
const open = this.state.anchorEl === null ? false : true;
const id = this.state.open ? 'simple-popper' : null;
return(
<section>
<button onClick={this.handlePopper}>Color</button>
<Popper
id={id}
open={this.state.open}
anchorEl={this.state.anchorEl}
transition
>
{({ TransitionProps }) => (
<Fade {...TransitionProps} timeout={350}>
<Paper>Content of popper.</Paper>
</Fade>
)}
</Popper>
</section>
)
}
}
答案 0 :(得分:1)
这些是我注意到的东西。
const id and open
,这不是必需的尝试此代码。
export class Toolbar extends PureComponent<IToolbarProps, IToolbarState> {
constructor(props) {
super(props);
this.state = {
anchorEl: null,
open: false,
};
}
flipOpen = () => this.setState({ open: !this.state.open });
handlePopper = (event: React.MouseEvent<HTMLElement>) => {
this.setState({ anchorEl: event.currentTarget });
this.flipOpen();
};
render() {
const open = this.state.anchorEl === null ? false : true;
const id = this.state.open ? "simple-popper" : null;
return (
<section>
<button onClick={this.handlePopper}>Color</button>
<Popper
id="simple-popper"
open={this.state.open}
anchorEl={this.state.anchorEl}
transition
>
{({ TransitionProps }) => (
<Fade {...TransitionProps} timeout={350}>
<Paper>Content of popper.</Paper>
</Fade>
)}
</Popper>
</section>
);
}
}