2015-12-07 58 views
0

我可以聲明一個組件數組嗎?並返回某些組件... 這是可能的?在ReactJS中,我可以聲明一個組件數組嗎?並返回某個組件

ES6:

import React from 'react'; 
import Component1 from './Component1'; 
import Component2 from './Component2';</br> 

export default App extends React.Component { 
    render() { 
    const myComponents = [`<Component1 />`,`<Component2 />`]; 

    return (
     {myComponents.map((component, index) => { 
     return component[index] === index; 
     })} 
    ); 
    } 
} 

建議PLS ..非常感謝

回答

2

當然有可能將它們存儲在陣列中。請記住,JSX只是常規Javascript的語法糖 - 它不是魔術,它不是一個字符串,所以不需要引用它。

const myComponents = [<Component1 />, <Component2 />]; 

以上JSX只是寫這篇短方式:

var myComponents = [ 
    React.createElement(Component1, null), 
    React.createElement(Component2, null) 
]; 

您在返回呈現有價將會雖然給你的問題。

mycomponents.map((component, index) => { 
    // this will always return false 
    // because objects are not numbers 
    return component[index] === index; 
}); 

這個對map的調用總是返回一個錯誤值的數組。如果您嘗試渲染它們,會引發錯誤。

相反,您可以渲染整個組件的數組。

return (
    <div>{ myComponents }</div> 
); 
+1

如果您想對已被標記爲可接受解決方案的答案進行低估,至少在評論中留下一些建設性的批評意見。 –

+0

對不起老兄。我只是誤了窗口..我的壞:( – vistajess

+0

謝謝(Y),朋友。我只是意識到,我回到我的地圖falsey值。:) – vistajess

相關問題