[英]How can I call a component inside a loop
I want to call a CategoryProduct component inside a forEach loop in the CategoryBox Component. 我想在CategoryBox组件的forEach循环内调用CategoryProduct组件。
My input : 我的输入 :
- productos = [ { header: 'car', src: 'picture.jpg', description: 'the car' } ]
CategoryProduct component: 产品类别:
@CategoryProduct = React.createClass
render: ->
div
className: 'CategoryProduct'
div
className: 'header'
@props.header
div
className: 'picture'
@props.src
div
className: 'description'
@props.description
Then I try to call the CategoryProduct component in the CategoryBox component: 然后,我尝试在CategoryBox组件中调用CategoryProduct组件:
@CategoryBox = React.createClass
render: ->
div
className: 'CategoryBox'
@props.productos.forEach (prod) ->
React.createElement CategoryProduct, { header: prod.header, src: prod.src, description: prod.description }
But the output is nothing. 但是输出是什么。 I did a console log inside the loop and is getting in without problem but it doesn't go inside the CategoryProduct component 我在循环内做了一个控制台日志,没有问题,但是没有进入CategoryProduct组件
Array.prototype.forEach()
doesn't return anything . Array.prototype.forEach()
不返回任何内容 。 You have to use Array.prototype.map()
instead. 您必须改为使用Array.prototype.map()
。
So your code should look like this 所以你的代码应该像这样
@CategoryBox = React.createClass
render: ->
div
className: 'CategoryBox'
@props.productos.map(prod) ->
React.createElement CategoryProduct, { header: prod.header, src: prod.src, description: prod.description }
You should look into coffeescript's loops and comprehensions . 您应该研究coffeescript的循环和理解力 。 They are much nicer than the JS ones and due coffeescripts implicit return, the loop will return an array containing the values on the last line inside the loop. 它们比JS更好,并且由于coffeescripts隐式返回,因此循环将返回包含循环内最后一行值的数组。
For example: 例如:
a = [1,2,3,4,5,6]
b = for item in a
z = item * 2
z + 1
Then b
would be [3, 5, 7, 9, 11, 13]
那么b
将是[3, 5, 7, 9, 11, 13]
So your code would read: 因此,您的代码将显示为:
@CategoryBox = React.createClass
render: ->
div
className: 'CategoryBox'
for prod in @props.productos
React.createElement CategoryProduct, prod
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.