reactjs - ReactJS 中无需重复代码的多个下拉菜单

标签 reactjs drop-down-menu dropdown

我在state的帮助下创建了下拉菜单onMouseOver。到目前为止,它的工作效果足够好。因为我对 ReactJS 没有太多了解,所以我不确定是否可以使用此方法或不同的方法创建多个下拉列表,而无需一遍又一遍地编写所有代码。

这是我的代码:

  ..........
  constructor(props) {
      super(props);
      this.handleMouseOver = this.handleMouseOver.bind(this);
      this.handleMouseLeave = this.handleMouseLeave.bind(this);
      this.state = {
        isHovering: false
      }
  }
  handleMouseOver = e => {
    e.preventDefault();
    this.setState({ isHovering: true });
  };
  handleMouseLeave = e => {
    e.preventDefault();
    this.setState({ isHovering: false })
  };

 ............

 <ul className="menu">
   <li onMouseOver={this.handleMouseOver} onMouseLeave={this.handleMouseLeave}>Categories
     {this.state.isHovering?(
       <ul className="dropdown">
         <li>Computerss & Office</li>
         <li>Electronics</li>
       </ul>
     ):null}
    </li>
  </ul>

 ............

因此,如果我想再添加一个下拉列表,我需要在 constructor() 中创建新的 state 和另外 2 行,以及 2 个函数来处理 MouseOver/Leave.So重复金额大约是这样的:

  constructor(props) {
      super(props);
      this.handleMouseOver = this.handleMouseOver.bind(this);
      this.handleMouseLeave = this.handleMouseLeave.bind(this);
      this.state = {
        isHovering: false
      }
  }
  handleMouseOver = e => {
    e.preventDefault();
    this.setState({ isHovering: true });
  };
  handleMouseLeave = e => {
    e.preventDefault();
    this.setState({ isHovering: false })
  };

我可能会有 10 多个下拉菜单,最后会加载大量代码。那么有没有可能不重复代码呢?谢谢!

最佳答案

您应该使用您的event.target来实现您想要的。这样,您就会知道您将鼠标悬停在哪个下拉菜单上,并应用您需要的任何逻辑。例如,您可以检查您悬停的下拉列表是否是类别下拉列表,如下所示:

if(e.target.className === "class name of your element")
this.setState({hoveredEl: e.target.className})

然后你可以在代码中使用它来显示/隐藏你想要的元素。

你可以查看我创建的这个 fiddle 的示例:https://jsfiddle.net/n5u2wwjg/153708/

我认为您不需要 onMouseLeave 事件,但如果您需要,可以遵循我应用于 onMouseOver 的逻辑

希望有帮助。

关于reactjs - ReactJS 中无需重复代码的多个下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52011166/

相关文章:

javascript - React JS - 调用作为 prop 传递的函数

asp.net - DropDownList selectedvalue 和表

选择 jquery,空字符串作为选项

java - 如何将旋转单选更改为多选

php - 基于两个下拉菜单显示数据库结果

babeljs - React 服务器端渲染意外 token 、JSX 和 Babel

javascript - react typescript : property 'body' does not exist type 'DefaultTheme'

node.js - 如何使用服务器端渲染设置 react-helmet?

css - 需要下拉菜单在页面加载时具有一定的宽度,但在单击时显示完整的内容长度

html - overflow-x 破坏了我的下拉导航栏