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

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 />
};
主站蜘蛛池模板: 炉霍县| 平凉市| 浮山县| 白银市| 平江县| 虞城县| 乌鲁木齐市| 库尔勒市| 资溪县| 屯门区| 泰安市| 涞水县| 正安县| 龙井市| 霍城县| 高青县| 平顺县| 芜湖市| 潼关县| 大宁县| 万源市| 措美县| 楚雄市| 彝良县| 会宁县| 东源县| 黄山市| 怀化市| 桐乡市| 营口市| 阜康市| 若尔盖县| 靖远县| 北海市| 星子县| 西昌市| 菏泽市| 景宁| 柞水县| 丰顺县| 扶沟县|