[英]ReactJS - How to create tabs dynamically?
我对ReactJS和react-tabs感到困惑。 我想在React中动态创建选项卡及其内容。 我有这个功能:
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>
);
}
}
在this.data.shops中的数据具有以下结构
0: "testStore"
1: "testStore2"
我想要实现的结果是:
<ReactTabs.TabList>
<ReactTabs.Tab>testStore</ReactTabs.Tab>
<ReactTabs.Tab>testStore2</ReactTabs.Tab>
</ReactTabs.TabList>
但是如何根据this.state.shops
中的数据动态创建这两个选项卡?
您只需要显示动态生成的组件的列表,而不能在纯JSX中执行此操作。
执行此操作最简洁的方法如下:
<ReactTabs.TabList>
{ this.state.shops.map(shop => <ReactTabs.Tab>{shop}</ReactTabs.Tab>) }
</ReactTabs.TabList>
您可以根据列表返回标签,例如:
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
方法将返回所有值yourDataList
一个接一个。
谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.