"使用React實作動態變數"
P粉008829791
P粉008829791 2023-09-02 20:55:54
0
1
441
<p>我在React中有以下程式碼:</p> <pre class="brush:js;toolbar:false;">const TABS = [ { value: "Names", label: "Names", onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected, }, { value: "Logs", label: "Logs", onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected, }, { value: "Groups", label: "Groups", onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected, }, { value: "Subscriptions", label: "Subscriptions", onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected, }, ] </pre> <p>我試圖將程式碼變成動態的,如下所示:</p> <pre class="brush:js;toolbar:false;">const values = ["Names","Logs","Groups","Subscriptions"]; const labels = ["Names","Logs","Groups","Subscriptions"]; const TABS = [ { value: {values}, label: {labels}, onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected, }] </pre> <p>我是對的嗎? </p>
P粉008829791
P粉008829791

全部回覆(1)
P粉904405941

使用:

const values = ["Names", "Logs", "Groups", "Subscriptions"];

const TABS = values.map((e, i) =>
    {
        return {
            value: e,
            label: e,
            onclick: (obj) => {
                tabOnClick(obj.value);
            },
            selected: mainTabSelected,
        }
    }
)

這將在您的values數組上映射每個元素,並為每個選項卡在Tabs數組中註入新物件。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板