【问题标题】:why if-else condition is not working while using in react jsx为什么在反应jsx中使用if-else条件不起作用
【发布时间】:2016-08-23 10:14:47
【问题描述】:

在编写反应代码时在 jsx 中编写 if-else 不起作用。

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

但是使用三元运算符是可行的。

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

为什么会这样?

【问题讨论】:

  • 因为if 不是右值?

标签: javascript reactjs react-jsx jsx


【解决方案1】:

你的 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。


您可以改为使用 immediately-invoked function expression 并传递从内部返回的值:

<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!"
);

【讨论】:

    【解决方案2】:

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

    【讨论】:

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

      因此,您会看到 if/else 不适合此模型。最好在 jsx 之外使用它。 可能在渲染函数中。

      【讨论】:

        猜你喜欢
        • 2020-12-05
        • 2016-07-24
        • 2018-09-12
        • 1970-01-01
        • 2014-03-21
        • 1970-01-01
        • 2018-10-16
        • 2014-03-25
        • 2020-03-11
        相关资源
        最近更新 更多