繁体   English   中英

需要在标签中更改活动类(反应)

[英]Need Change active class in tab ( react)

如果我单击第二页,重新加载页面后,所有选项卡都会获得CURRENT类,如何解决这个问题? 如何在第一个TAB上禁用当前类? 如果我删除activeClassName =“current”,重新加载当前类后切换到第一个选项卡,但我看到第二个选项卡内容

 import React from 'react'
import { Link, browserHistory,IndexLink } from 'react-router'




class Tabs extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
              index: ''                
        };
        this.onclick = this.onclick.bind(this);
    }

    onclick(index) {
        this.setState({index});
    }

    getListItem(){
        let numbers = this.props.menuitems;
        let listItems = numbers.map((item,index) =>
                <li

                  onClick={this.onclick.bind(this, index)} key={index}>

          <Link to={item.link} activeClassName="current"
           className={index == this.state.index? "tab-link current" : "tab-link"}>{item.linkName}</Link>
                  </li>
        );
        return listItems;
    }

    render() {
        return (
            <div>
                <ul className="tabs" >{this.getListItem()}</ul>
                <div className="tabs-header-stripe"></div>
            </div>
        );
    }
}
export default Tabs

根据您描述的场景,您需要一个stateful component而不是stateless function component 将当前选项卡的索引存储在状态变量中并在onclick方法中更新它,在rendering过程中将状态变量的索引与项目的索引进行比较,如果它们相同则应用该类。 试试这个类似的例子,它应该在你的情况下工作:

class HelloWidget extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
              index: ''                
        };
        this.onclick = this.onclick.bind(this);
    }

    onclick(index) {
        this.setState({index});
    }

    getListItem(){
        let numbers = this.props.menuitems;
        let listItems = numbers.map((item,index) =>
                <li style={{color: this.state.index==index?'red': 'black'}} className={this.state.index == index ? "tab-link current" : "tab-link"} onClick={this.onclick.bind(this, index)} key={index}>{index}-{item.number}</li>
        );
        return listItems;
    }

    render() {
        return (
            <div>
                <ul className="tabs" >{this.getListItem()}</ul>
                <div className="tabs-header-stripe"></div>
            </div>
        );
    }
}

React.render(<HelloWidget menuitems={[{number:0, index:0}, {number:1, index:1}, {number:3, index:3}]}/>, document.getElementById('container'));

检查jsfiddle的工作示例: httpsjsfiddle

className current仅在第一个选项卡上,因为您正在检查index === 0(第一个选项卡),如果为true,则表示您正在添加当前类。

您需要保持activeTabIndex状态,并在onClick函数上将activeTabIndex更改为正确的索引。

然后你可以检查

className={index === this.state.activeTabIndex ? "tab-link current" : "tab-link"}

暂无
暂无

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

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