You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中实现Triple conditional rendering(三重条件渲染)的方法

三重条件渲染实现方案

修复后完整可运行代码

import { useState } from 'react'

const TripleConditionalRendering = () => {
  const [color, setColor] = useState("")

  const handleClickRed = () => {
    setColor("red")
  }
  const handleClickBlue = () => {
    setColor("blue")
  }
  // 修复原有重复声明handleClickRed的错误,补充绿色点击事件
  const handleClickGreen = () => {
    setColor("green")
  }

  // 实现方式1:多分支三元运算,适合少量固定分支场景
  return (
    <>
      <button onClick={handleClickRed}>红色</button>
      <button onClick={handleClickBlue}>蓝色</button>
      <button onClick={handleClickGreen}>绿色</button>

      {color === 'red' ? (
        <p>the color is : red</p>
      ) : color === 'blue' ? (
        <p>the color is : blue</p>
      ) : color === 'green' ? (
        <p>the color is : green</p>
      ) : <p>请选择颜色</p>}
    </>
  )

  // 实现方式2:对象映射法,适合分支多、后续有扩展可能的场景,维护成本更低
  /*
  const colorRenderMap = {
    red: <p>the color is : red</p>,
    blue: <p>the color is : blue</p>,
    green: <p>the color is : green</p>
  }
  return (
    <>
      <button onClick={handleClickRed}>红色</button>
      <button onClick={handleClickBlue}>蓝色</button>
      <button onClick={handleClickGreen}>绿色</button>
      {color ? colorRenderMap[color] : <p>请选择颜色</p>}
    </>
  )
  */
}

核心改动说明

  • 修复原有代码重复声明handleClickRed的语法错误,补充绿色点击事件的逻辑
  • React要求组件返回单个根节点,使用<></>(空片段)包裹所有元素符合语法要求
  • 修正原条件判断中字符串red未加引号的语法错误
  • 两种实现方案可选:
    • 多分支三元运算:逻辑直观,适合3个及以内的固定分支场景
    • 对象映射:后续新增颜色分支时只需在映射对象中新增配置即可,无需修改判断逻辑,扩展性更强

内容的提问来源于stack exchange,提问作者pedrofromperu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 05:09:03