- 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 /> };
推薦閱讀
- Mastering Visual Studio 2017
- WebAssembly實(shí)戰(zhàn)
- Boost C++ Application Development Cookbook(Second Edition)
- 從程序員到架構(gòu)師:大數(shù)據(jù)量、緩存、高并發(fā)、微服務(wù)、多團(tuán)隊(duì)協(xié)同等核心場(chǎng)景實(shí)戰(zhàn)
- Python機(jī)器學(xué)習(xí)實(shí)戰(zhàn)
- SQL基礎(chǔ)教程(視頻教學(xué)版)
- 青少年P(guān)ython編程入門(mén)
- Node.js:來(lái)一打 C++ 擴(kuò)展
- Android項(xiàng)目實(shí)戰(zhàn):手機(jī)安全衛(wèi)士開(kāi)發(fā)案例解析
- Python Interviews
- Python 3 數(shù)據(jù)分析與機(jī)器學(xué)習(xí)實(shí)戰(zhàn)
- ActionScript 3.0從入門(mén)到精通(視頻實(shí)戰(zhàn)版)
- Qt 4開(kāi)發(fā)實(shí)踐
- Python預(yù)測(cè)分析與機(jī)器學(xué)習(xí)
- Oracle Database XE 11gR2 Jump Start Guide