在reactjs中使用es6映射的意外标记

时间:2017-04-01 04:57:22

标签: javascript reactjs ecmascript-6

我在jsx中有这个像breadcrumb = ['food','hotdogt']这样的数组,但我得到unexpected token .的错误?

{breadcrumb.map(obj => {
   {obj}
})}

1 个答案:

答案 0 :(得分:0)

像这样写:

{
    breadcrumb.map(obj => {
         return <div> {obj} </div>
    })
}

{
   breadcrumb.map(obj => <div> {obj} </div>)
}

{
   breadcrumb.map(obj => obj)
}
{}元素中使用js代码时,需要

html大括号,您使用{obj}但未使用任何html元件。你也忘了使用return

检查此示例:

&#13;
&#13;
var breadcrumb = ['food','hotdogt'];

var App = () => {
   return(
       <div>
          {
             breadcrumb.map(obj => <p key={obj}> {obj} </p>)
          }
          {
             breadcrumb.map((obj, i) => { 
                return <span key={obj}>
                           <span className="bold"> {obj} </span> 
                           {i != breadcrumb.length -1 ? <span className="seperator"> -> </span> : null} 
                       </span>
             })
          }
       </div>
   )
}

ReactDOM.render(<App/>, document.getElementById('app'))
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>
&#13;
&#13;
&#13;