简体   繁体   English

React应用程序-IconMenu在Click事件上未展开。

[英]React app - IconMenu not expanded on Click event.

I need help with react app and IconMenu from material-ui. 我需要来自Material-ui的React App和IconMenu的帮助。 Studying many similar issues without results :( 研究许多没有结果的类似问题:(

Having following code, I want to trigger menu expand manually - I need it in tests framework to simulate clicking on submenu item. 具有以下代码,我想手动触发菜单展开-我需要在测试框架中模拟子菜单项上的单击。

const Menu = () => {
    return (
        <IconMenu 
            iconButtonElement={<FlatButton style={{height: '100%'}
            }
            onClick={() => console.log('clicked!')}
            label={'FooLabel'}
            labelPosition='before'
            />}>
            <MenuItem primaryText="submenu" leftIcon={<SignOutIcon />} />
        </IconMenu>
    );
};

The problem is that, when I do click on menu item, the onClick event is triggered, but menu is not expanded at all: 问题是,当我单击菜单项时,会触发onClick事件,但菜单根本不会展开:

demo: https://imgur.com/32RzHcB 演示: https : //imgur.com/32RzHcB

I was trying to send custom event by dispatchEvent function, but even onClick is not triggered. 我试图通过dispatchEvent函数发送自定义事件,但是即使onClick也不会触发。 Is something what i missed? 是我想念的东西吗?

It looks like by using onClick you override the default behaviour, so you'll need to use IconMenu's open prop and tell it when you want it to be open (true) or closed (false). 看起来,通过使用onClick可以覆盖默认行为,因此,您需要使用IconMenu的open属性,并在希望它打开(true)或关闭(false)时告诉它。

You'll need to have some code in your component that toggles open between true and false. 您需要在组件中有一些代码在true和false之间切换open To do this, the component will need to be stateful instead of functional. 为此,该组件将需要是有状态的,而不是功能性的。 If you haven't done this before, check out the react docs on converting a function to a class 如果您以前没有做过,请查看有关将函数转换为类的react文档

Try: 尝试:

class Menu extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      menuOpen: false
    };
  }

  _toggleOpen = () => {
    this.setState({
      menuOpen: !this.state.menuOpen
    });
  };

  _handleClick = () => {
    this._toggleOpen();
    // .. do your other on click stuff here
  }

  render(
    <IconMenu 
        iconButtonElement={<FlatButton style={{height: '100%'}
        }
        onClick={this._handleClick}
        label={'FooLabel'}
        labelPosition='before'
        open={this.state.menuOpen}
        />}>
        <MenuItem primaryText="submenu" leftIcon={<SignOutIcon />} />
    </IconMenu>
  );
}

so now we've got a state that the Menu component can update which will decide whether the menu should be open and which gets passed down into the open prop. 因此,现在我们有了菜单组件可以更新的状态,它将决定是否应打开菜单以及将其传递给打开的道具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM