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

cczfrluj  于 2022-12-12  发布在  React
关注(0)|答案(2)|浏览(213)

我有一个下拉菜单,其中有一个嵌套的菜单,如下所示。

展开后的下拉菜单显示两个选项:

问题是在单击任何项目时,Tenant Name或Dealer ID下的子选项会显示一秒钟,然后消失。如何解决此问题,接下来是如何存储用户选择的值?
我的代码如下:

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>
  );
 }
}
tkclm6bt

tkclm6bt1#

要获取用户选择的值,您需要绑定一个onChange事件,如

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

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

不知道为什么你的列表会出现一秒钟。检查控制台,看看它是否显示任何错误。你仍然可以尝试 Package 你的材料ui组件

<MuiThemeProvider>

但我认为你错过了webpack中的一些加载程序,这可能是为什么行为不寻常的原因
这是我的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]
           }
      ]

   }
};
jjjwad0x

jjjwad0x2#


让我们看看下面的源代码,它可以帮助你建立更多的理解:

Dropdown.js这是一个Dropdown组件类,它帮助我们呈现下拉菜单内容。当用户单击下拉菜单时,此组件类将在浏览器中呈现更新的下拉菜单列表。
显示下拉菜单:此方法有助于显示下拉菜单内容。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这是下拉菜单的样式表设计。

.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这是帮助显示下拉菜单的主要组件。

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();

相关问题