【发布时间】:2019-01-29 08:38:57
【问题描述】:
我是 React 的初学者。我刚刚尝试了以下代码:
class Contact extends React.Component {
render() {
return (
<div id="authorization">
<h1>
{
if (this.state.authorized) {
'Contact'
} else {
'Enter the Password'
}
}
</h1>
)
}
}
正如你在上面的代码中看到的,我在一对花括号 {} 之间放了一个 JS if-else 代码,因为我读过它 Introducing JSX那个
您可以将任何有效的 JavaScript 表达式放在 JSX 中的花括号内。
但是上面的代码不起作用。但是如果我用三元运算符替换它:
<h1>
{ this.state.authorized ? 'Contact' : 'Enter the Password' }
</h1>
有效!是不是在某些情况下我只能使用三元运算符而不能使用通常的 JS if-else 语句?
【问题讨论】:
标签: javascript reactjs if-statement ternary-operator