2017-02-12 92 views
0
{item.status} 
<div className="{item.status !== '' ? 'hide' : ''} pull-right">Content</div> 

为什么上面的jsx没有效果?我的item.status值是字符串。但在我的DOM中,我看不到添加了隐藏类。JXS if else class does not work

回答

3

这是因为你在“,所以它是作为字符串处理包裹的三元操作试试这个:

{item.status} 
<div class={"pull-right "+(item.status !== '' ? 'hide' : '')}>Content</div> 
+0

如果我想使用if else条件而不是添加hide类,该怎么办? –

+0

您可以将整个组件包装在三元运算符中,例如{item.status!==''?null:

Content
} –

0

除了什么@拉胡尔 - 普拉塔普 - 辛格说,可以考虑使用美观大方,微型封装称为classnames - link here所以你可以使用它像:

import classes from 'classnames'; 

// later on 
<div className={classes({ 
    "pull-right": true, 
    "hide": item.status !== '', 
})} /> 

我认为它会导致更清洁的代码不是加入串

还是在。最少使用es6字符串插值 - link here

// instead of 
"pull-right "+(item.status !== '' ? 'hide' : '') 

// with string interpolation 
`pull-right ${item.status.length ? '' : 'hide'}`;