簡體   English   中英

ReactJS-如何動態創建標簽?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM