我的页面顶部有一个选项卡导航,我想在单击该选项卡时向该选项卡添加一个“事件”类,并确保它不在任何其他选项卡上。
到目前为止,我已将“事件”类添加到第一个选项卡,但如果您单击任何其他选项卡则不会更新。因此,无论您单击什么,第一个选项卡始终是事件选项卡。
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/