JSX是JavaScrip的一种扩展语法,JSX的标签语法既不是字符串也不是HTML;
从本质上讲,JSX只是为React.createElement(component, props, ...children)函数提供的语法糖。javascript
写jsx模板的时候,咱们遇到循环输出子组件或者标签,须要经过Array.forEach或者for循环输出;判断选择子组件的时候,须要经过if或者三元判断输出;一个模板里面咱们会不少逻辑,这些逻辑看起来跟jsx不是很和谐!有没有办法作到标签化,跟jsx语法一致尼?css
安装html
npm install --save-dev babel-plugin-jsx-control-statements
配置.babelrcjava
{ ... "plugins": ["jsx-control-statements"] }
If(可是目前不支持Else,这也是惋惜的)react
// 简单例子 <If condition={ true }> <span>IfBlock</span> </If> // 使用多个子元素或者表达式 <If condition={ true }> one { "two" } <span>three</span> <span>four</span> </If> // 转化前 <If condition={ test }> <span>Truth</span> </If> // 转化后 { test ? <span>Truth</span> : null }
Choose、When、Otherwise( 至关于switch case defualt)git
// 转化前 <Choose> <When condition={ test1 }> <span>IfBlock1</span> </When> <When condition={ test2 }> <span>IfBlock2</span> </When> <Otherwise> <span>ElseBlock</span> </Otherwise> </Choose> // 转化后 { test1 ? <span>IfBlock1</span> : test2 ? <span>IfBlock2</span> : <span>ElseBlock</span> }
Forgithub
// 循环输出的时候必须提供key <For each="item" of={ this.props.items }> <span key={ item.id }>{ item.title }</span> </For> // 若是数组改变,则使用索引做为键属性是不稳定的 <For each="item" index="idx" of={ [1,2,3] }> <span key={ idx }>{ item }</span> <span key={ idx + '_2' }>Static Text</span> </For>