当前位置: 首页 > news >正文

React JSX 使用条件语句渲染UI的两种写法

只针对函数组件

1. 第一种写法:

function App({ id }) {return id==1? <h1>hello</h1> : <h1>world</h1>;
}

或者:

function App({ id }) {return (<h1>{id==1 && "hello" || id==2 && "world" || "unknown"}</h1>)
}

2. 如果需要条件细分,第二种写法

function App({ id }) {let content = ""if (id==1) {content = "hello" //如果包含html标签,默认会被转义}else if (id==2) {content = "world"}return (<h1>{content}</h1>);
}

3. 第三种写法:

function App({ id }) {return (<h1>{(()=>{if (id==1) {return "hello"}else if (id==2) {return "world"}})()}</h1>);
}

switch同理:

function App({ id }) {return (<h1>{(()=>{switch(id) {case 1:return "hello"case 2:return "world"default:return "unknown"}})()}</h1>);
}


http://www.mrgr.cn/news/51441.html

相关文章:

  • 软件测试面试200问,面试看这就够了。。。
  • StaccaToe 机器人:动态运动与精密控制的融合
  • 楼宇智慧公厕的几个功能需要哪些硬件支持
  • 【华为云开发者空间实践指导】基于FunctionGraph实现Gif动图制作应用开发
  • uniapp 小程序0到1教程
  • 某协程旅行 - sign、token
  • java代码生成器集成dubbo,springcloud详解以及微服务遐想
  • 100. UE5 GAS RPG 显示范围魔法的攻击范围
  • Unity-Shader-SubShader CG代码块
  • 例行性工作(at,crontab)
  • 【Linux】了解pthread线程库,清楚并没有线程创建接口,明白Linux并不存在真正意义的线程(附带模型图详解析)
  • OGG错误:ORA-28000:the account is locked
  • js实现简单的【发布者-订阅者模式】
  • 工信部 | 信息技术应用创新人才证书哪个科目好考?
  • 栈的压入、弹出序列
  • vector使用与实现
  • 基于华为昇腾910B,实战 InternLM2.5-7B-Chat 模型推理
  • 还在百度搜PDF工具,完全免费的神器推荐给你-PDF24工具箱!
  • Vue2组件
  • 神经网络模型量化代码解析