[英]ReactJS - How to create tabs dynamically?
I am bit stuck with ReactJS and react-tabs. 我对ReactJS和react-tabs感到困惑。 I want to dynamically create tabs and their contents in React.
我想在React中动态创建选项卡及其内容。 I have this function:
我有这个功能:
class MyLog extends React.Component{
constructor(props){
// Pass props to parent class
super(props);
// Set initial state
this.state = {
data: [],
shops: [],
}
this.apiListUrl = '/backend/MyLog/listApi';
this.apiStoreUrl = '/backend/MyLog/storeApi';
}
componentDidMount(){
// Make HTTP request with Axios
axios.get(this.apiListUrl)
.then((res) => {
// Set state with result
this.setState({data:res.data.data});
});
axios.get(this.apiStoreUrl)
.then((res) => {
// Set state with result
this.setState({shops:res.data.data});
});
}
render(){
// Render JSX
return (
<div>
<Title />
<ReactTabs.Tabs>
<ReactTabs.TabList>
<ReactTabs.Tab>Title 1</ReactTabs.Tab>
</ReactTabs.TabList>
<ReactTabs.TabPanel>Contents 1</ReactTabs.TabPanel>
</ReactTabs.Tabs>
</div>
);
}
}
In this.data.shops is the data with the following structure 在this.data.shops中的数据具有以下结构
0: "testStore"
1: "testStore2"
I want to achieve that the results are: 我想要实现的结果是:
<ReactTabs.TabList>
<ReactTabs.Tab>testStore</ReactTabs.Tab>
<ReactTabs.Tab>testStore2</ReactTabs.Tab>
</ReactTabs.TabList>
But how can I create these two tabs dynamically on basis of the data in this.state.shops
? 但是如何根据
this.state.shops
中的数据动态创建这两个选项卡?
You just need to display a list of dynamically generated components, you can't do this in pure JSX. 您只需要显示动态生成的组件的列表,而不能在纯JSX中执行此操作。
The most concise way for doing this is the following: 执行此操作最简洁的方法如下:
<ReactTabs.TabList>
{ this.state.shops.map(shop => <ReactTabs.Tab>{shop}</ReactTabs.Tab>) }
</ReactTabs.TabList>
You can return the tabs based on your list like: 您可以根据列表返回标签,例如:
render(){
// Render JSX
return (
<div>
<Title />
<ReactTabs.Tabs>
<ReactTabs.TabList>
{this.bindTabs()}
</ReactTabs.TabList>
<ReactTabs.TabPanel>Contents 1</ReactTabs.TabPanel>
</ReactTabs.Tabs>
</div>
);
}
bindTabs(){
return yourDataList.map(item)=>{
<ReactTabs.Tab>item.title</ReactTabs.Tab>
}
}
bindTabs
method will return all the value from yourDataList
one by one. bindTabs
方法将返回所有值yourDataList
一个接一个。
Thanks 谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.