简体   繁体   English

如何使用 Material UI 在 React JS 中实现下拉菜单?

[英]How to implement dropdown menu in React JS using Material UI?

I have a dropdown which has a nested menu as shown below.我有一个下拉菜单,它有一个嵌套菜单,如下所示。

在此处输入图片说明

The dropdown upon expanding shows two options:展开时的下拉列表显示两个选项:

在此处输入图片说明

The problem is upon clicking any of the items the children options under Tenant Name or Dealer ID display for a second and disappear.问题是在单击租户名称或经销商 ID 下的子选项中的任何项目时会显示一秒钟并消失。 How to solve this problem and next is how to store values which the user selects?如何解决这个问题,接下来是如何存储用户选择的值?

My code is as follows:我的代码如下:

   export default class DropDownMenuSimpleExample extends React.Component {

 constructor(props) {
super(props);
this.state = {
  dropDownData: [
    {
      value: '',
      tenantName: '',
      dealerId: '',
    },
  ],
};
}

handleChange = (event, index, value) => {
    this.setState({ value });
    console.log(event, index, value);
 }

render() {
 return (

  <DropDownMenu
      style={styles.customWidth}
      anchorOrigin={{ horizontal: 'left', vertical: 'top' }}
      targetOrigin={{ horizontal: 'left', vertical: 'top' }}
      className={{ backgroundcolor: '#CFD8DC' }}

  >

    <MenuItem
        value={this.state.value}
        onChange={this.handleChange}
        primaryText="TENANT NAME"
        rightIcon={<ArrowDropRight />}
        menuItems={[
          <MenuItem value={100} primaryText="CA-CAR" />,
          <Divider />,
          <MenuItem value={101} primaryText="TEKION" />,
        ]}
    />

    <MenuItem
        value={this.state.value}
        onChange={this.handleChange}
        primaryText="DEALER ID"
        rightIcon={<ArrowDropRight />}
        menuItems={[
          <MenuItem value={1} primaryText="1" />,
          <MenuItem value={2} primaryText="2" />,
          <MenuItem value={3} primaryText="2" />,
          <MenuItem value={4} primaryText="4" />,
        ]}
    />
  </DropDownMenu>
  );
 }
}

to get values that user selects you need to bind a onChange event like要获取用户选择的值,您需要绑定一个 onChange 事件,例如

<SelectField  onChange={(evt,index,name) =>this.getOccasion(name) />

getOccasion()
{
this.setState({
//update to state
})
}

no idea why your list appears for a second.Check console and see if it shows any error.Still you can try to wrap your material ui components in不知道为什么您的列表会出现一秒钟。检查控制台,看看它是否显示任何错误。您仍然可以尝试将您的材料 ui 组件包装在

<MuiThemeProvider>

but think you have missed some loaders in webpack may be thats why the behaviour is unusual但是认为您错过了 webpack 中的一些加载程序,这可能就是这种行为不寻常的原因

Here is my webpack configuration see if it helps这是我的 webpack 配置,看看它是否有帮助

const postcssPlugins = [
  require('postcss-cssnext')(),
  require('postcss-modules-values')
];

const scssLoader = [
  { loader: 'style-loader' },
  { loader: 'css-loader' },
  { loader: 'sass-loader' }
];

const postcssLoader = [
  { loader: 'style-loader' },
  { loader: 'css-loader', options: { modules: true } },
  { loader: 'postcss-loader', options: { plugins: () => [...postcssPlugins] } }
];

var path = require('path');

module.exports = {
          entry: './src/main/resources/static/js/app.js',
          output: {
            path: __dirname + '/src/main/resources/static/js', 
            filename: 'bundle.js' 
          },

  module: {
      loaders: [
         {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',

            query: {
               presets: ['es2015', 'react']
            }
         },
         {
             test: /\.(scss|sass)$/,
             loader: scssLoader,
             include: [__dirname]
           },
           { test: /\.css$/,
             loader: postcssLoader,
             include: [__dirname]
           }
      ]

   }
};

在此处输入图片说明 Lets see the below source code, which help you to build more understanding:让我们看看下面的源代码,它可以帮助您建立更多的理解:

Dropdown.js This is a Dropdown component class, which help us to render the dropdown menu content. Dropdown.js这是一个 Dropdown 组件类,它帮助我们渲染下拉菜单内容。 When user click on the dropdown menu, then this component class render the updated dropdown menu list in browser.当用户单击下拉菜单时,该组件类在浏览器中呈现更新的下拉菜单列表。

showDropdownMenu : This method helps to display the dropdown menu content. showDropdownMenu :此方法有助于显示下拉菜单内容。 hideDropdownMenu : This method helps to hide the dropdown menu content. hideDropdownMenu :此方法有助于隐藏下拉菜单内容。

import React from 'react';
import './style.css';


class Dropdown extends React.Component {
constructor(){
 super();

 this.state = {
       displayMenu: false,
     };

  this.showDropdownMenu = this.showDropdownMenu.bind(this);
  this.hideDropdownMenu = this.hideDropdownMenu.bind(this);

};

showDropdownMenu(event) {
    event.preventDefault();
    this.setState({ displayMenu: true }, () => {
    document.addEventListener('click', this.hideDropdownMenu);
    });
  }

  hideDropdownMenu() {
    this.setState({ displayMenu: false }, () => {
      document.removeEventListener('click', this.hideDropdownMenu);
    });

  }

  render() {
    return (
        <div  className="dropdown" style = {{background:"red",width:"200px"}} >
         <div className="button" onClick={this.showDropdownMenu}> My Setting </div>

          { this.state.displayMenu ? (
          <ul>
         <li><a className="active" href="#Create Page">Create Page</a></li>
         <li><a href="#Manage Pages">Manage Pages</a></li>
         <li><a href="#Create Ads">Create Ads</a></li>
         <li><a href="#Manage Ads">Manage Ads</a></li>
         <li><a href="#Activity Logs">Activity Logs</a></li>
         <li><a href="#Setting">Setting</a></li>
         <li><a href="#Log Out">Log Out</a></li>
          </ul>
        ):
        (
          null
        )
        }

       </div>

    );
  }
}

export default Dropdown;

style.css This is a style sheet design for the drop-down menu. style.css 这是下拉菜单的样式表设计。

 .dropdown {
     position: relative;
     display: inline-block;
}
 ul {
     list-style-type: none;
     margin: 0;
     padding: 0;
     top:45px;
     right:0px;
     width: 200px;
     background-color: white;
     font-weight:bold;
     position: absolute;

     box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
     z-index: 1;
}
 li a {
     color: #000;
     text-decoration: none;
}
 li {
     padding: 8px 16px;
     border-bottom: 1px solid #e5e5e5;
}
 li:last-child {
     border-bottom: none;
}
 li:hover {
     background-color: #e5e5e5;
     color: white;
}
 .button{
     width:178px;
     height:18px;
     background-color:#ff3232 ;
     padding:12px;
     border-radius:5px;
     font-weight:bold;
     color:white;
}
 .button:before{
     content:"";
     position:absolute;
     width:0px;
     height:0px;
     border: 10px solid;
     border-color: white transparent transparent transparent;
     right:6px;
     top:18px;

} }

index.js This is a main component which helps to display the dropdown menu. index.js 这是一个帮助显示下拉菜单的主要组件。

import React from 'react';
import ReactDOM from 'react-dom';
import registerServiceWorker from './registerServiceWorker';
import Dropdown from './dropdownmenu/Dropdown';


var displayDropdown = (
      <div style={{display: 'flex', justifyContent: 'center'}} >
        <Dropdown />
      </div>
      );

ReactDOM.render(displayDropdown, document.getElementById('root'));

registerServiceWorker();

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

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