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

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 />
};
主站蜘蛛池模板: 平湖市| 万山特区| 塘沽区| 榆中县| 龙川县| 娄烦县| 灌阳县| 邳州市| 富川| 孟州市| 芮城县| 富顺县| 海盐县| 英德市| 龙口市| 黔南| 舞阳县| 石林| 巢湖市| 铜陵市| 天水市| 车致| 松溪县| 安仁县| 临颍县| 辽宁省| 邵阳市| 峨眉山市| 罗甸县| 巍山| 石景山区| 探索| 军事| 甘谷县| 澄城县| 阿坝| 德昌县| 广州市| 芜湖市| 梅河口市| 邳州市|