如何在单击按钮时动态添加标签
我尝试了所有示例,但没有一个对我有帮助
例如:- 下面最初有两个引导程序选项卡,分别名为Tab1和Tab2 .. 添加标签按钮在那里。 当我们单击该标签时,tab3需要自动绑定 这个家伙怎么给我建议呢?
答案 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);