【问题标题】: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>
为什么会这样?
【问题讨论】:
标签:
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 之外使用它。
可能在渲染函数中。