在 React JS 的 If 条件下处理状态值

Handling state value in If condition in React JS

几天前我开始使用语义 UI,最近遇到了一个问题,但我还没有找到答案。如何在 if 条件下处理 class 的状态值?

我想在这里做的是制作一个侧边菜单,该菜单仅在用户单击按钮时显示,而在用户单击显示菜单之外时隐藏。类似于 Semantic 的侧边栏,但没有整个 .pusher 组件。

所以基本上我需要一个 if 条件来检查 "visible" 状态值,如果它等于 'none',则将其更改为 'block'(启用显示),反之亦然。 到目前为止,我编码如下:

import React, { Component } from 'react'
import { Input, Label, Menu } from 'semantic-ui-react'

export class SidebarMenuEX extends Component {

constructor(props)
{
    super(props);
    this.state = {activeItem: 'inbox', visible: 'none'};
}

handleItemClick = (e, { name }) => this.setState({ activeItem: name })

handleDisplay(){
if {this.state[visible]} = 'none'
this.setState({visible = 'block'})
}

render() {
const { activeItem } = this.state.activeItem
const { visible } = this.state.visible

return (
  <Menu vertical display = 'none'>
    <Menu.Item name='inbox' active={activeItem === 'inbox'} onClick={this.handleItemClick}>
      <Label color='teal'>1</Label>
      Inbox
    </Menu.Item>

    <Menu.Item name='spam' active={activeItem === 'spam'} onClick={this.handleItemClick}>
      <Label>51</Label>
      Spam
    </Menu.Item>

    <Menu.Item name='updates' active={activeItem === 'updates'} onClick={this.handleItemClick}>
      <Label>1</Label>
      Updates
    </Menu.Item>
    <Menu.Item>
      <Input icon='search' placeholder='Search mail...' />
    </Menu.Item>
  </Menu>
)
}

显然我的 handleDisplay() 方法不起作用,但我想了解为什么 If 条件不能将 this.state.visiblethis.state[visible] 识别为有效(它说 [js] ':'预期的)。有谁知道解决这个问题的方法?谢谢!

D.

使用有效 JS 语法的答案是:

if (this.state.visible === 'none') {
  this.setState({visible: 'block'});
}