在JSX中使用<If><Choose><When><Otherwise>等逻辑标签

前端之家收集整理的这篇文章主要介绍了在JSX中使用<If><Choose><When><Otherwise>等逻辑标签前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

默认JSX不支持此类标签,我们需要一个插件来实现.
jsx-control-statements提供了这个功能.

安装

npm install --save-dev jsx-control-statements

语法

If

// simple
<If condition={ true }>
  <span>IfBlock</span>
</If>

// using multiple child elements and / or expressions
<If condition={ true }>
  one
  { "two" }
  <span>three</span>
  <span>four</span>
</If>

Choose

<Choose>
  <When condition={ test1 }>
    <span>IfBlock</span>
  </When>
  <When condition={ test2 }>
    <span>ElseIfBlock</span>
    <span>Another ElseIfBlock</span>
    <span>...</span>
  </When>
  <Otherwise>
    <span>ElseBlock</span>
  </Otherwise>
</Choose>

// default block is optional; minimal example:
<Choose>
  <When condition={true}>
    <span>IfBlock</span>
  </When>
</Choose>

When & Otherwise

// Before transformation
<Choose>
  <When condition={ test1 }>
    <span>IfBlock1</span>
  </When>
  <When condition={ test2 }>
    <span>IfBlock2</span>
  </When>
  <Otherwise>
    <span>ElseBlock</span>
  </Otherwise>
</Choose>

// After transformation
{ test1 ? <span>IfBlock1</span> : test2 ? <span>IfBlock2</span> : <span>ElseBlock</span> }

For

// you must provide the key attribute yourself
  <For each="item" of={ this.props.items }>
    <span key={ item.id }>{ item.title }</span>
  </For>

  // using the index as key attribute is not stable if the array changes
  <For each="item" index="idx" of={ [1,2,3] }>
    <span key={ idx }>{ item }</span>
    <span key={ idx + '_2' }>Static Text</span>
  </For>

github

https://github.com/AlexGilleran/jsx-control-statements

原文链接:https://www.f2er.com/react/306478.html

猜你在找的React相关文章