【问题标题】:Passing array into React stateless component将数组传递给 React 无状态组件
【发布时间】:2019-09-18 06:14:07
【问题描述】:

按照 Learn 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 不是函数”。 当我删除解构的things (const App = () => ...) 时,我的组件工作了。

我的问题是: 1. 当things 都用const 声明并且可能不在同一范围内时,things 是如何被拉入 App() 的,并且things 没有被专门传递到函数中? 2. 如果我做了一些不同的事情,示例代码对我有用吗?

谢谢!

【问题讨论】:

    标签: javascript reactjs pure-function


    【解决方案1】:

    props在使用createElement时传入组件:

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

    第一个 sn-p 就是这样做的。第二个没有,因此局部变量things 将是undefined,因此您不能对其进行迭代。如果你想访问一个全局变量,你只需要确保没有同名的局部变量,所以这也可以:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-20
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 2022-07-15
      • 2019-09-29
      • 2018-01-15
      • 2021-09-09
      相关资源
      最近更新 更多