- ReactJS by Example:Building Modern Web Applications with React
- Vipul A M Prathamesh Sonpatki
- 146字
- 2021-07-09 19:37:00
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 /> };
推薦閱讀
- Flask Web全棧開發實戰
- WordPress Plugin Development Cookbook(Second Edition)
- 從Excel到Python:用Python輕松處理Excel數據(第2版)
- C/C++程序員面試指南
- C專家編程
- Python青少年趣味編程
- Practical GIS
- Hacking Android
- Mastering Concurrency in Python
- 進入IT企業必讀的324個Java面試題
- Hands-On Dependency Injection in Go
- Less Web Development Cookbook
- C語言程序設計實驗指導
- Cloud Development andDeployment with CloudBees
- Rust Quick Start Guide