材质UI Popper锚点El状态未更改

时间:2020-08-03 13:45:18

标签: javascript reactjs material-ui popper

我正在使用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>
                )
            }
    }

1 个答案:

答案 0 :(得分:1)

这些是我注意到的东西。

  • 锚定设置为空,这不是必需的
  • 在filpOpen中传播状态,这不是必需的
  • 构造函数未正确关闭
  • 不确定为什么我们有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>
    );
  }
}
相关问题