将数组传递到React无状态组件

时间:2019-04-29 15:27:50

标签: javascript reactjs pure-function

以下是《学习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应用,并在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不是函数”。 当我删除变形的thingsconst App = () => ...)时,我的组件正常工作。

我的问题是:     1.当thingsconst都声明为things且可能不在同一范围内,并且src="https://example.com/public/images/someimage.jpg?itok=WDGFySy"没有专门传递到函数中时,如何将它们{?itok=WDGFySy中拉入App()?     2.如果执行其他操作,示例代码对我有用吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

使用createElement时,道具被传递到组件中:

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

第一个代码段就是这样做的。第二个不是,因此局部变量things将是undefined,因此您不能对其进行迭代。如果要访问全局变量,只需确保没有任何局部变量具有相同的名称,因此这也可以工作:

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