当我们使用React js和Bootsrap 4单击按钮时如何动态添加选项卡

时间:2019-07-19 07:30:09

标签: reactjs bootstrap-4

如何在单击按钮时动态添加标签

我尝试了所有示例,但没有一个对我有帮助

例如:-     下面最初有两​​个引导程序选项卡,分别名为Tab1和Tab2 ..     添加标签按钮在那里。     当我们单击该标签时,tab3需要自动绑定     这个家伙怎么给我建议呢?

参考链接:- https://www.bootply.com/61679

1 个答案:

答案 0 :(得分:2)

我想这将是您在React中完成此功能所需的基本模板。

在此处查看此沙箱:https://codesandbox.io/s/romantic-wiles-w2uwh

工作代码:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
  state = {
    tabs: [
      { name: "Tab 1", content: "Wow this is tab 1" },
      { name: "Tab 2", content: "Look at me, it's Tab 2" }
    ],
    currentTab: { name: "Tab 1", content: "Wow this is tab 1" }
  };

  createTabs = () => {
    const { tabs, currentTab } = this.state;

    const allTabs = tabs.map(tab => {
      return (
        <li>
          <button
            className={currentTab.name == tab.name ? "tab active" : "tab"}
            onClick={() => this.handleSelectTab(tab)}
          >
            {tab.name}
          </button>
        </li>
      );
    });

    return <ul className="nav nav-tabs">{allTabs}</ul>;
  };

  handleSelectTab = tab => {
    this.setState({
      currentTab: tab
    });
  };

  handleAddTab = () => {
    const { tabs } = this.state;

    const newTabObject = {
      name: `Tab ${tabs.length + 1}`,
      content: `This is Tab ${tabs.length + 1}`
    };

    this.setState({
      tabs: [...tabs, newTabObject],
      currentTab: newTabObject
    });
  };

  render() {
    const { currentTab } = this.state;
    return (
      <div className="container">
        <div className="well">
          <button className="add-tab-button" onClick={this.handleAddTab}>
            <i className="text-primary fas fa-plus-square" /> Add Tab
          </button>
          {this.createTabs()}
          <div className="tab-content">{currentTab.content}</div>
        </div>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);