简体   繁体   English

如何让我的菜单逻辑更简洁?

[英]How can I make my menu logic more concise?

The code below updates my menu system.下面的代码更新了我的菜单系统。 Each menu items is in an if statement.每个菜单项都在一个 if 语句中。

The problem is that I have to set the style for each item.问题是我必须为每个项目设置样式。 So as I add items the logic gets huge.所以当我添加项目时,逻辑变得很大。

The menu of course turns its corresponding div on and off.菜单当然会打开和关闭其相应的 div。

How can I make this more concise?我怎样才能使这个更简洁?

var style_1;
var style_268;
var style_280;
if (this.props.MenuFave.current === '1') {
  style_1 = {
    display: 'inline-block'
  };
  style_280 = {
    display: 'none'
  };
  style_268 = {
    display: 'none'
  };
}
if (this.props.MenuFave.current === '280') {
  style_280 = {
    display: 'inline-block'
  };
  style_1 = {
    display: 'none'
  };
  style_268 = {
    display: 'none'
  };
}
if (this.props.MenuFave.current === '268') {
  style_268 = {
    display: 'inline-block'
  };
  style_280 = {
    display: 'none'
  };
  style_1 = {
    display: 'none'
  };
}

JSX JSX

  <div id = 'fave_hold'>
    <div className = 'faves' id = 'fave_hold_arc' style={style_1} >
      {tags1}
    </div>
    <div className = 'faves' id = 'fave_hold_news' style={style_280}>
      {tags280}
    </div>
    <div className = 'faves' id = 'fave_hold_sw' style={style_268}>
      {tags268}
    </div>
  </div>

You can just hide menu item, do not render:您可以只隐藏菜单项,不渲染:

{this.props.MenuFave.current !== '1' ? (
<div className = 'faves' id = 'fave_hold_arc' >
  {tags1}
</div>
) : null}
....

You can do it inside your JSX as follows:您可以在 JSX 中执行以下操作:

<div id = 'fave_hold'>
    {this.props.MenuFave.current === '1'?
    <div className = 'faves' id = 'fave_hold_arc'  >
      {tags1}
    </div>:null}
    {this.props.MenuFave.current === '280'?
    <div className = 'faves' id = 'fave_hold_news' >
      {tags280}
    </div>:null}
    {this.props.MenuFave.current === '268'?
    <div className = 'faves' id = 'fave_hold_sw' >
      {tags268}
    </div>:null}
 </div>

Create an object with all of your values and object deconstruct使用您的所有值和对象解构创建一个对象

const menuStyles = {
  1: {
    display_1: 'inline-block',
    display_280: 'none',
    display_268: 'none'
  },
  280: {
    display_1: 'none',
    display_280: 'inline-block',
    display_268: 'none'
  },
  268: {
    display_1: 'none',
    display_280: 'none',
    display_268: 'inline-block'
  }
}
const currentStyle = menuStyles[this.props.MenuFave.current]
const {display_1, display_280, display_268} = currentStyle
const style_1 = {display: display_1}
const style_268 = {display: display_268}
const style_280 = {display: display_280}

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

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