如何让菜单逻辑更简洁?

时间:2017-10-05 01:39:05

标签: javascript reactjs redux jsx

以下代码更新了我的菜单系统。每个菜单项都在if语句中。

问题是我必须为每个项目设置样式。因此,当我添加项目时,逻辑会变得很大。

菜单当然会打开和关闭相应的div。

我怎样才能使这更简洁?

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

  <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>

3 个答案:

答案 0 :(得分:1)

你可以隐藏菜单项,不要渲染:

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

答案 1 :(得分:0)

您可以在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>

答案 2 :(得分:0)

创建一个包含所有值和对象解构的对象

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}