【问题标题】:How to use conditional ternary operator for jsx react? [closed]如何使用条件三元运算符进行 jsx 反应? [关闭]
【发布时间】:2020-05-26 07:10:01
【问题描述】:

我想根据 isOpen 值返回 null 或 jsx。

下面是我的代码,

function Child ()  {
    const isOpen = true;
    return (
        <Fragment>
            <wrapper>
                <div> title</div>
                <button> click me </button>
            </wrapper>
        </Fragment>
    )
}

如何使用三元运算符根据 isOpen 值返回 null 或上述 jsx。如果它是真的,它应该返回 jsx 如果不​​为空。

有人可以帮我解决这个问题吗?谢谢。

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

您实际上不需要三元运算符来执行此操作。

  1. 如果isOpen == false返回null:
function Child ()  {
    const isOpen = true;

    if (!isOpen) return null;

    return (
        <Fragment>
            <wrapper>
                <div> title</div>
                <button> click me </button>
            </wrapper>
        </Fragment>
    )
}
  1. 使用&amp;&amp;运算符:
function Child ()  {
    const isOpen = true;
    return isOpen && (
        <Fragment>
            <wrapper>
                <div> title</div>
                <button> click me </button>
            </wrapper>
        </Fragment>
    )
}

【讨论】:

    【解决方案2】:

    只需使用三元:

    function Child ()  {
        const isOpen = <whatever-condition>;
        return (
            isOpen ?
            <Fragment>
                <wrapper>
                    <div> title</div>
                    <button> click me </button>
                </wrapper>
            </Fragment>
            : null
        )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-15
      • 1970-01-01
      • 2020-05-10
      • 2010-09-28
      相关资源
      最近更新 更多