[英]react map method - put callback function separately and send arguments
The map method takes a callback function as I've understood it. 据我所知,map方法采用了回调函数。 Normally you would put the function inside map:
通常,您可以将函数放在map中:
const todoItems = todos.map((todo) =>
<li key={todo.id}>
{todo.text}
</li>
);
But in my project I call the function as a separate component: 但是在我的项目中,我将该函数称为一个单独的组件:
{ tabs.map( myFunction ) }
here is the myFunction component: 这是myFunction组件:
const myFunction = (item) => {
return(
<Thing
key={item.value}
label={item.label}
value={item.value}
/>
);
}
The "item" from map seems to be passed automatically. 地图中的“商品”似乎是自动传递的。
The problem is that I need to pass an extra variable - how do I do it? 问题是我需要传递一个额外的变量-我该怎么做? This doesn't work:
这不起作用:
{ tabs.map( myFunction(myvariable) ) }
nor: 也不:
{ tabs.map((styles) => myFunction ) }
So I'm unsure how to pass the variable..and still get the "item" passed as well. 所以我不确定如何传递变量..并且仍然获得“ item”传递。
Solution is: 解决方法是:
{ tabs.map((tab) => myFunction(tab, myvariable)) }
Also note that 另请注意
const myFunction = (item) => {
return(
<Thing
key={item.value}
label={item.label}
value={item.value}
/>
);
}
could be refactored into 可以重构为
const myFunction = (item) => (
<Thing
key={item.value}
label={item.label}
value={item.value}
/>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.