【问题标题】:How to conditionally display custom tag in react jsx如何在反应jsx中有条件地显示自定义标签
【发布时间】:2021-07-14 22:41:57
【问题描述】:

我正在尝试根据 React 中变量的值有条件地显示自定义标签。

值来自表单上下文。

例如:

return( 
   ...

   (formContext = {
       const variable = getVariable() // returns a string

   
....

   <custom tag> </custom tag>

我只想在变量值与某个字符串匹配时显示自定义标签,例如: 如果变量为“DISP”,则仅显示标签。

请,谢谢。

如果您需要更多信息,请告诉我。

【问题讨论】:

  • 你想显示什么标签? getVariable 是否返回标签名称?或者您只想在条件为真时 conditionally render 自定义标签?
  • getVariable 只返回一个字符串。我想根据该字符串的值显示标签。

标签: html reactjs jsx


【解决方案1】:

使用条件渲染

{ (variable === "DISP") && <custom tag> </custom tag> }

【讨论】:

    【解决方案2】:

    您可以为此使用条件渲染。

    return (
      { (variable === "string") && <customTag></customTag> }
    )
    

    要了解有关自定义渲染的更多信息,您可以阅读以下内容:https://reactjs.org/docs/conditional-rendering.html#:~:text=Inline%20If%20with%20Logical%20%26%26%20Operator&text=Therefore%2C%20if%20the%20condition%20is,will%20return%20the%20falsy%20expression

    【讨论】:

      猜你喜欢
      • 2021-04-18
      • 1970-01-01
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-23
      相关资源
      最近更新 更多