1.9 如何根据不同的条件进行不同的内容渲染

一、使用条件语句

  1. if

    function App() {
      let content
      const count = 3
      if (count > 1) {
        content = <div> hello </div>
      } else {
        content = <p>123</p>
      }
    
      return <>{content}</>
    }
    
    export default App
    

    注意:适合做多个条件的渲染

  2. 条件运算符(三元运算符):? :

    function App() {
      // let content
      const count = 3
      // if (count > 1) {
      //   content = <div> hello </div>
      // } else {
      //   content = <p>123</p>
      // }
    
      return <>{count > 3 ? <div> hello </div> : <p>123</p>}</>
    }
    
    export default App
    

    注意:适合做多个条件的渲染

  3. 逻辑运算符:&&, ||

    1. 哪些值不会渲染:布尔值、空字符、null、对象、函数

    2. 如何对不渲染的值进行输出:JSON.stringify(),{undefined + ''}

    function App() {
      return (
        <>
          <div>hello</div>
          {0 && <div> world </div>}
        </>
      )
    }
    
    export default App
    

    注意:适合做一个条件的渲染

  4. switch

最后更新于