默认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