簡體   English   中英

將數組傳遞給React無狀態組件

[英]Passing array into React stateless component

按照學習ReactJS的示例,我嘗試以相同的方式傳遞數組只會產生錯誤。

來自作者的Github示例: https//github.com/MoonHighway/learning-react/blob/master/chapter-04/03-react-components/04-components.html

 const IngredientsList = ({items}) =>
        React.createElement("ul", {className: "ingredients"},
            items.map((ingredient, i) =>
                React.createElement("li", { key: i }, ingredient)
            )
        )
    const items = [
        "1 lb Salmon",
        "1 cup Pine Nuts",
        "2 cups Butter Lettuce",
        "1 Yellow Squash",
        "1/2 cup Olive Oil",
        "3 cloves of Garlic"
    ]
    ReactDOM.render(
      React.createElement(IngredientsList, {items}, null),
      document.getElementById('react-container')
    )

我用create-react-app啟動了一個React應用create-react-app ,並在App.js中編寫了以下內容:

const things = [
    'foo',
    'bar',
    'baz',
    'fizz',
    'buzz'
];

const App = ({things}) =>
    React.createElement("ul",{className: "thingsAndStuff"},
    things.map((item, value) =>
        React.createElement("li", {key:value}, item)
        )
    );

在index.js中,我將ReactDom.render作為:

ReactDOM.render(React.createElement(App, null, null), document.getElementById('root'));

我收到錯誤“things.map not a function”。 當我刪除了結構化的thingsconst App = () => ... )時,我的組件工作了。

我的問題是:1。當使用const聲明並且可能不在同一范圍內時,如何將things拉入App(),並且things沒有特別傳遞到函數中? 2.如果我做了不同的事情,示例代碼是否適用於我?

謝謝!

使用createElement時, props會傳遞到組件中:

  React.createElement(App, /*props:*/ { things });

第一個片段就是這樣做的。 第二個沒有,因此局部變量的things將是undefined ,因此你不能迭代它。 如果要訪問全局變量,只需確保沒有本地變量具有相同的名稱,因此這也可以:

const App = () => React.createElement("ul",
     { className: "thingsAndStuff" },
     things.map((item, value) =>
        React.createElement("li", {key:value}, item)
     )
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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