以编程方式切换 Reactstrap NavItem

Switching Reactstrap NavItem programmatically

嗨 Reactjs / Reactstrap 专家-

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

我试图让 Reactstrap 的 Nav 和 Navlink 根据按钮点击从一个选项卡切换到另一个选项卡。在我下面的代码笔页面中,当在选项卡 1 上单击 "Go to Tab 2" 时会出现空白视图,而当我单击选项卡 2 中的 "Go to Tab 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"));

您将字符串 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')
}

这是更新后的代码笔 link:https://codepen.io/anon/pen/rQEbOJ?editors=0010