官术网_书友最值得收藏!

Conditionals in JSX

"React embraces the idea of tying markup and logic that generates the markup together. This means that we can use the power of JavaScript for loops and conditionals."

"But if/else logic is a bit hard to express in markup. Therefore, in JSX, we can't use conditional statements such as if/else."

// Using if/else directly doesn't work
<p className={if(success) { 'green' } else { 'red' }}/>
Error: Parse Error: Line 1: Unexpected token if

"Instead, we can use a ternary operator for specifying the if/else logic."

// Using ternary operator
<p className={ success ? 'green' : 'red' }/>
React.createElement("p", {className:  success ? 'green' : 'red'})

"But ternary operator gets cumbersome with large expressions when we want to use the React component as a child. In this case, it's better to offload the logic to a block or maybe a function" Mike added.

// Moving if/else logic to a function
var showResult = function() {
  if(this.props.success === true)
    return <SuccessComponent />
  else
    return <ErrorComponent />
};
主站蜘蛛池模板: 永新县| 三台县| 通渭县| 萨嘎县| 五寨县| 龙州县| 文水县| 洪江市| 井研县| 通道| 葫芦岛市| 景谷| 满洲里市| 安宁市| 灵山县| 封开县| 铜鼓县| 延吉市| 海林市| 康乐县| 运城市| 岐山县| 新化县| 浦东新区| 探索| 崇阳县| 梨树县| 丹阳市| 清镇市| 定南县| 汶上县| 竹溪县| 延川县| 庄浪县| 德江县| 冷水江市| 杨浦区| 淳安县| 克东县| 内黄县| 和林格尔县|