javascript - react 映射运算符

标签 javascript reactjs jsx

我试图声明一个变量“ratingVal”,它在 map 运算符内分配了一个随机的“否”。我想在评级组件中使用该变量并将其显示在屏幕上。但是我收到错误

Parsing error: Unexpected token

在这种情况下声明变量的正确语法是什么?

renderProductsCardsList(products){

   return products.map(
     (product, i) =>

       let ratingVal = Math.floor(Math.random() * 5) + 1
       <Rating initialRating={ratingVal} readonly></Rating>
       <div>{ratingVal}</div>
   )
}

最佳答案

箭头函数中不能有带有隐式返回的声明语句。为此,请使用显式返回语法。此外,您不能从 map 方法中返回多个元素。将它们包裹在<React.Fragment>内:

renderProductsCardsList(products){
   return products.map(
     (product, i) => {
       let ratingVal = Math.floor(Math.random() * 5) + 1
       return (
            <React.Fragment>
                <Rating initialRating={ratingVal} readonly></Rating>
                <div>{ratingVal}</div>
             </React.Fragment>
       )
   })
}

或在分配时对其进行评估

renderProductsCardsList(products){
   return products.map(
     (product, i) => 
            <React.Fragment>
                <Rating initialRating={Math.floor(Math.random() * 5) + 1} readonly></Rating>
                <div>{ratingVal}</div>
             </React.Fragment>
   )
}

关于javascript - react 映射运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54751163/

相关文章:

javascript - 如何检测到达底部时是否溢出的表格 [jQuery]

javascript - Redux 路由器 - "Dispatch is not defined"

javascript - 如何在其他站点嵌入 React 组件?

javascript - sails.js:刷新之前,新创建的记录不会填充在页面上

javascript - 使用对象扩展运算符构造带字段的函数对象

javascript - 设置密码输入的默认值,以便可以读取

javascript - 这个 useState 钩子(Hook)在 React 中是如何工作的?

node.js - 禁用未找到 eslint 规则的警告消息

javascript - e.target.classList 在 react typescript 中的 onClick 事件中不存在

javascript - 像 var a = (xml code) 这样的 JS 语法是如何工作的?