猿问

如何根据 If 条件的结果渲染 React 组件?

有什么简单的方法可以根据 if 条件的结果将 React 组件渲染到 App.js 中?我有时钟应用程序,当我定义的闹钟值等于当前时间时,它应该“响铃”。这个“响铃”效果我想成为另一个组件,例如 Ring.js 将在当前时间等于闹钟时间时呈现,并且它将包含来自状态 a 的文本我可以通过单击按钮简单地卸载它。


这是我的函数,它每秒调用一次,以检查 alarmHours 状态是否有值。


  function checkTime(){

   if(time.alarmHours && time.alarmMinutes){

    if(time.currentHour === time.alarmHours && time.currentMinute === time.alarmMinutes && 

     time.currentSecond === '00'){

      //VALUES ARE EQUAL ,ALARM IS RINGING,RENDER COMPONENT

     }

    }

   }

我的第一个想法是创建空变量,如果满足条件,只需将 Ring.js 组件插入该变量即可。


let ring;


function checkTime(){

  if(time.alarmHours && time.alarmMinutes){

    if(time.currentHour === time.alarmHours && time.currentMinute === time.alarmMinutes && 

    time.currentSecond === '00'){

      ring = <Ring />

    }

  }

}

然后,只需在 App.js 的 Return() 中渲染该变量,就像这样。


Return(

  <div>

    {ring}

  </div>

)

但它不起作用,什么都没有呈现。


我试图查看官方 React 文档,他们提供的示例很少,但我真的不知道如何在我的案例中实施该方法。如果满足该条件,我不知道如何呈现该组件。有人可以帮我吗?我会很感激的。谢谢你。


codesandbox 链接:https ://codesandbox.io/s/rough-paper-xv0wi?file=/src/App.js


梵蒂冈之花
浏览 187回答 2
2回答

慕慕森

如果准备就绪,我会更新您的checkTime()函数以返回<Ring />,否则返回 null 然后您可以:return (&nbsp; <div>&nbsp; &nbsp; {checkTime()}&nbsp; </div>);IEfunction checkTime(){&nbsp; if(time.alarmHours && time.alarmMinutes){&nbsp; &nbsp; if(time.currentHour === time.alarmHours && time.currentMinute === time.alarmMinutes &&&nbsp;&nbsp; &nbsp; time.currentSecond === '00'){&nbsp; &nbsp; &nbsp; return <Ring />&nbsp; &nbsp; }&nbsp; }&nbsp; return null;}ring不再需要。编辑:评论中的附加问题如果您想Ring显示何时达到闹钟时间,我会更改模式并引入一个新的布尔状态值,例如const [showRing, setShowRing] = React.useState(false)最初设置为 false 的值。checkTime()然后将不再返回任何 JSX 并且只是调用setShowRing(true)然后你会:return (&nbsp; <div>&nbsp; &nbsp; {showRing && <Ring />}&nbsp; </div>);IEfunction checkTime(){&nbsp; if(time.alarmHours && time.alarmMinutes){&nbsp; &nbsp; if(time.currentHour === time.alarmHours && time.currentMinute === time.alarmMinutes &&&nbsp;&nbsp; &nbsp; time.currentSecond === '00'){&nbsp; &nbsp; &nbsp; setShowRing(true);&nbsp; &nbsp; }&nbsp; }}无论你想删除<Ring />你会打电话setShowRing(false)

潇湘沐

试试这个:let ring = <Ring />;function checkTime(){&nbsp; if(time.alarmHours && time.alarmMinutes){&nbsp; &nbsp; if(time.currentHour === time.alarmHours && time.currentMinute === time.alarmMinutes &&&nbsp;&nbsp; &nbsp; time.currentSecond === '00'){&nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }&nbsp; }&nbsp; &nbsp;return false;}...return (&nbsp; <div>&nbsp; &nbsp;{checktime() ? ring : null}&nbsp; </div>)
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答