为什么if-else条件在react jsx中使用时不起作用

why if-else condition is not working while using in react jsx

本文关键字:不起作用 jsx if-else 条件 react 为什么      更新时间:2023-09-26

在编写react代码的同时在jsx中编写if-else不起作用。

<div id={if (condition) { 'msg' }}>Hello World!</div>

然而,使用三元运算符是可行的。

<div id={condition ? 'msg' : null}>Hello World!</div>

为什么会发生这种情况?

的JSX

<div id={condition ? 'msg' : null}>Hello World!</div>

其本身不是有效的Javascript,将被编译为以下ReactJS调用:

React.createElement(
  'div',                            // Element "tag" name.
  { id: condition ? 'msg' : null }, // Properties object.
  'Hello World!'                    // Element contents.
);

有效的Javascript,可由您的Javascript运行时环境进行解释/编译。正如您所看到的,没有办法将if-else插入该语句中,因为它无法编译成有效的Javascript。


您可以使用一个立即调用的函数表达式,并传递从中返回的值:

<div id={(function () {
    if (condition) {
        return "msg";
    } else {
        return null;
    }
})()}>Hello World!</div>

它将编译成以下有效的Javascript:

React.createElement(
    "div",
    {
        id: (function () {
            if (condition) {
                return "msg";
            } else {
                return null;
            }
        })()
    },
    "Hello World!"
);

if else语句在JSX中不起作用。这是因为JSX只是函数调用和对象构造的语法糖。React Docs

// This JSX:
<div id={if (condition) { 'msg' }}>Hello World!</div>
// Is transformed to this JS:
React.createElement("div", {id: if (condition) { 'msg' }}, "Hello World!");

因此,您可以看到/else是否不适合此模型。最好在jsx之外使用它。可能处于渲染功能中。