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

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 />
};
主站蜘蛛池模板: 伽师县| 临江市| 彭山县| 株洲市| 阿拉尔市| 平昌县| 邢台市| 文水县| 运城市| 介休市| 郯城县| 海口市| 远安县| 湖南省| 凤凰县| 通城县| 余江县| 固镇县| 沂水县| 大洼县| 迁安市| 瑞丽市| 嘉善县| 梧州市| 潜山县| 吴忠市| 吉首市| 高淳县| 鹤庆县| 平定县| 汉源县| 根河市| 沙坪坝区| 分宜县| 洛隆县| 故城县| 永兴县| 巧家县| 莱阳市| 体育| 灵山县|