React.js (jsx)中的一行条件语句



我有一个React应用程序,我使用JSX,我有一个条件是:如果输入被选择(即为真)通过搜索引擎传递一个特定的查询。我还想在相同的条件下添加背景样式,所以我想到了以下内容:

<div style={ui.selected.thisInput && {background: "red"} }></div>

我也试过:

<div style={{ ui.selected.thisInput ? "background:red" }}></div>

都抛出错误。

你可以这样做:

<div {...(condition ? { style: { background: 'red' } } : {})}></div>

<div style={condition ? { background: 'red' } : {}}></div>

作为当前的问题:

<div style={condition && { background: 'red' }}></div> // Wrong
当条件为true

时,将生成正确的样式,但当条件为condition时,将生成错误的样式,即style={false}

try this

<div style={{ background:condition?"red":"blue"}}>

<div style={{ background:condition?"red":""}}>

例子

最新更新