![](/img/trans.png)
[英]Trouble passing a function to a stateless functional component in 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”。 当我删除了结构化的things
( const 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.