【问题标题】:How to conditionally render a DIV and REACT component for OPENING and CLOSING tags?如何有条件地为 OPENING 和 CLOSING 标签呈现 DIV 和 REACT 组件?
【发布时间】:2023-04-08 10:24:02
【问题描述】:

我有一段代码应该根据应用的条件呈现。例如:

isMobile ? <MyComponent> : <div className={styles.myclassStyle}>

....other code goes here....

isMobile ? </MyComponent> : </div>

如果 isMobile 为真,则应选择 MyComponent 否则 html 元素
div 。有可能这样做吗?任何替代解决方案?

【问题讨论】:

    标签: html css reactjs


    【解决方案1】:

    您将有条件地渲染整段代码,并且您将不得不在括号中使用单个根元素返回它。比如说

    {
      isMobile ? (
        <MyComponent>
          // this code runs if isMobile === true
          // ... code for MyComponent
        </MyComponent>
      ) : (
        <div className={styles.myclassStyle}>
          // this code runs of isMobile === false
          // ... code for the div goes here
        </div>
      )
    }
    

    【讨论】:

    • 这会在代码中产生冗余。关键是使用条件语句来使用不同的组件。
    • 您在原始代码中尝试做的不是条件渲染的工作方式。您应该研究组件的组合,或者将该代码中的所有标记抽象到其他组件,以便您可以将其减少到 isMobile ? &lt;MyComponent /&gt; : &lt;AnActualComponentNotADiv /&gt; 并减少您编写的代码量。 react 是关于创建可重用的组件并优雅地组合它们
    • @Eid 信不信由你,它实际上没有你尝试的那么多余; 1 三元条件与 2。这是(其中一种)反应的惯用方式来有条件地呈现一个“事物”或“其他”。 reactjs.org/docs/conditional-rendering.html
    • @Michael,是的,我相信 React 不支持这种情况。
    猜你喜欢
    • 2011-10-19
    • 2019-06-28
    • 2019-10-03
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多