为什么在 react jsx 中使用时 if-else 条件不起作用
why if-else condition is not working while using in react jsx
在编写 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 运行时环境 interpreted/compiled。如您所见,无法将 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!"
);
// 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 之外使用它。
可能在渲染函数中。
if-else 语句在 JSX 中不起作用。这是因为 JSX 只是函数调用和对象构建的语法糖。
React Docs
在编写 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 运行时环境 interpreted/compiled。如您所见,无法将 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!"
);
// 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 之外使用它。 可能在渲染函数中。
if-else 语句在 JSX 中不起作用。这是因为 JSX 只是函数调用和对象构建的语法糖。 React Docs