javascript - React - 更新状态以从选项卡导航中添加/删除事件类

标签 javascript reactjs

我的页面顶部有一个选项卡导航,我想在单击该选项卡时向该选项卡添加一个“事件”类,并确保它不在任何其他选项卡上。

到目前为止,我已将“事件”类添加到第一个选项卡,但如果您单击任何其他选项卡则不会更新。因此,无论您单击什么,第一个选项卡始终是事件选项卡。

import React from 'react'
import { string } from 'prop-types'

class TabNav extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      currentTab: ''
    }

    this.handleClick = this.handleClick.bind(this)
    this.createTabItems = this.createTabItems.bind(this)
  }

  shouldComponentUpdate (nextProps, nextState) {
    return nextProps.navItems !== this.props.navItems
  }

  handleClick (currentTab) {
    this.setState({
      currentTab: currentTab
    })
    this.createTabItems()
  }

  createTabItems () {
    const { navItems = false } = this.props
    if (!navItems) return false
    const splitItems = navItems.split(',')
    if (!splitItems.length) return false
    return splitItems.map((item, currentTab) => {
      const items = item.split('_')
      if (items.length !== 3) return null
      const itemLink = items[1]
      return (
        <li key={currentTab} className={this.state.currentTab == currentTab ? 'side-nav-tab active' : 'side-nav-tab'} onClick={this.handleClick.bind(this, currentTab)}>
            <a href={itemLink}>
              <p>{ items[0] }</p>
            </a>
        </li>
      )
    })
  }

  render () {
    const tabItems = this.createTabItems()
    if (!tabItems) return null
    return (
      <div>
        <ul id='tabNavigation'>
          {tabItems}
        </ul>
      </div>
    )
  }
}

TabNav.propTypes = {
  navItems: string.isRequired
}

export default TabNav

我也曾尝试在 setState 中异步调用 this.createTabItems 以尝试强制更新,但没有成功:

 handleClick (currentTab) {
    this.setState({
      currentTab: currentTab
    }, () => this.createTabItems)
  }

最佳答案

我认为您的 shouldComponentUpdate 导致了这个问题。您可以尝试删除它吗?此外,您不需要在 handleClick()

中调用 this.createTabItems

关于javascript - React - 更新状态以从选项卡导航中添加/删除事件类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57077199/

相关文章:

javascript - react router v^4.0.0 Uncaught TypeError : Cannot read property 'location' of undefined

javascript - 如何在 React 中将参数传递给事件监听器?

javascript - Redux + React-router 组件不渲染

javascript - express-jwt 身份验证中间件不工作

javascript - Angular js : $injector:modulerr Module Error

javascript - 什么方法最适合在 JavaScript 中实例化其他函数的函数?

javascript - Twitter API 与 React JS

javascript - 使用 Flux 构建一个编辑表单,实际上是谁将数据 POST 到服务器 : actions, 存储、 View ?

reactjs - 如何在 react 中使用history.push

javascript - 使图像填充剩余的垂直空间,不滚动