以编程方式切换Reactstrap NavItem

问题描述 投票:0回答:1

嗨Reactjs / Reactstrap专家 -

我是ReactJS和Reactstrap的新手,我找不到一个通过JS演示NavItem切换的实例。

我试图让Reactstrap的Nav和Navlink根据按钮点击从一个标签切换到另一个标签。在下面的代码笔页面中,当单击“转到选项卡2”时,在选项卡1上导致空白视图,当我单击选项卡2中的“转到选项卡1”按钮时会发生同样的情况。我不知道我可以去哪里错误。

这是我的JS代码和code pen created based on the below code

能否请你帮忙?

const { TabContent, TabPane, Nav, NavItem, NavLink, Card, Button, CardTitle, CardText } = Reactstrap;

class App extends React.PureComponent {

  constructor() {    
    super();
    this.state = {
      activeTab: '1'
    };
    this.toggle = this.toggle.bind(this);
    this.switchToTab1 = this.switchToTab1.bind(this);
    this.switchToTab2 = this.switchToTab2.bind(this);
  }

   toggle(tab) {
        if (this.state.activeTab !== tab) {
            this.setState({
                activeTab: tab
            });
        }
    }

  switchToTab2() {
    this.toggle(2);
  }

  switchToTab1() {
    this.toggle(1);
  }

  render() {
    return (
      <React.Fragment>
        <Nav tabs className="card-header-tabs">
          <NavItem>
              <NavLink active={this.state.activeTab === '1'} onClick={() => { this.toggle('1'); }}>
                  Tab 1
              </NavLink>
          </NavItem>
          <NavItem>
              <NavLink active={this.state.activeTab === '2'} onClick={() => { this.toggle('2'); }}>
                  Tab 2
              </NavLink>
          </NavItem>
        </Nav>
          <div className="card-body">
            <TabContent activeTab={this.state.activeTab}>
              <TabPane tabId="1">
                <h1>Content from Tab 1</h1>
                <Button color="primary" onClick={this.switchToTab2}>Go to Tab 2</Button>
              </TabPane>
              <TabPane tabId="2">
                <h1>Content from Tab 2</h1>
                <Button color="primary" onClick={this.switchToTab1}>Go to Tab 1</Button>
              </TabPane>
            </TabContent>
         </div>
      </React.Fragment>
    );  
  }
}

ReactDOM.render(<App />, document.getElementById("app"));
reactjs reactstrap
1个回答
1
投票

您正在将字符串ID与数字ID混合,而在比较时您使用的是===(严格等式检查)Reference

问题在于你的toggle方法,你正在传递数字ID。它应该是传递字符串ID,它应该工作。

switchToTab2() {
   this.toggle(2); // It should be this.toggle('2')
}

switchToTab1() {
   this.toggle(1); // It should be this.toggle('1')
}

这是更新的codepen链接:https://codepen.io/anon/pen/rQEbOJ?editors=0010

© www.soinside.com 2019 - 2024. All rights reserved.