Reactjs: CJSX Nested Conditionals

大憨熊 提交于 2019-12-22 14:57:07

问题


What is the correct syntax to handle nested conditional logic in a React component?

React.createClass
render: ->
  <div>
    {if @props.showList
      {for item in @props.myItems
        {item}
      }
    else
    }
  </div>

The for loop (on its own) can be rendred; the if/else conditional (on its own) can be rendered. However, nesting the for loop inside the conditional fails.

Any help would be very much appreciated.


回答1:


I haven't tested it, but based on how normal JSX works you only need the {expression} thing to escape from JSX mode.

The program starts in JS mode (or CS here), and when an element tag is encountered it enters JSX mode. Using {foo} in JSX mode causes it to go back to JS mode. From there the above rules apply, and you can re-enter JSX mode by starting a tag, and so on.

render: ->
  <div>
    {
    if @props.showList
      for item in @props.myItems
        item

    else
       <div>{foo}</div>
    }
  </div>

With annotations:

CoffeeScript:

render: ->

JSX within CoffeeScript

  <div>

CoffeeScript within JSX within CoffeeScript

    {
    if @props.showList
      for item in @props.myItems
        item

    else

JSX within CoffeeScript within JSX within CoffeeScript

       <div>

CoffeeScript within JSX within CoffeeScript

          {foo}

JSX within CoffeeScript

       </div>

JSX within CoffeeScript

    }
  </div>

CoffeeScript

...



回答2:


Inside the {} sections you can just use normal Coffeescript/CJSX code, as long as it evaluates to a single expression:

React.createClass
  render: ->
    <div>
      {
        if @props.showList
          for item in @props.myItems
            <span key={item.id}>{item}</span>
        else
          <span>some other content</span>
      }
    </div>


来源:https://stackoverflow.com/questions/26876513/reactjs-cjsx-nested-conditionals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!