不能在 JSX 中呈现布尔值?

我试图在 JSX 中呈现布尔值,但是 React 将其作为表达式进行计算,并且在组件返回后不返回任何内容。

有什么解决办法吗?

这里有一个例子

var ipsumText = true;


ReactDOM.render(
<div>
Boolean Value:    {ipsumText}
</div>,
document.getElementById('impl')
);

只是将编译后的 HTML 显示为

<div data-reactid=".0"><span data-reactid=".0.0">Boolean Value:    </span></div>

编辑: 这里是示例 < a href = “ http://JSBin.com/nibihodoce/1/EDIT? html,js,output”rel = “ norefrer”> http://JSBin.com/nibihodoce/1/EDIT?html,js,output 的 JSBin 链接

编辑2: 我已经探索了。ToString ()替代,但是因为我迭代一个对象数组,并且该对象的一个特定字段可以具有字符串/整数/布尔类型的值。申请。ToString ()对于所有类似的函数似乎都不是最优的。

59652 次浏览

You can convert boolean value to string, concatenating it with empty string:

var ipsumText = true;


ReactDOM.render(
<div>
Boolean Value: {ipsumText + ''}
</div>,
document.getElementById('impl')
);

Or you can do it, when assigning bool value to variable:

var ipsumText = true + '';


ReactDOM.render(
<div>
Boolean Value: {ipsumText}
</div>,
document.getElementById('impl')
);

If your variable can have not boolean value, you should convert it to boolean:

// `ipsumText` variable is `true` now.
var ipsumText = !!'text';
Boolean Value: { ipsumText.toString() }

or

Boolean Value: { String(ipsumText) }

or

Boolean Value: { '' + ipsumText }

or

{`Boolean Value: ${ipsumText}`}

or

Boolean Value: { JSON.stringify(ipsumText) }

I prefer the second option. Universal, fast, works for all primitive types: Boolean( smth ), Number( smth ).

<select>
<option value={row.feature_product ? true: true || row.feature_product ? false: false}>
{`${row.feature_product}`}
</option>
<option value={row.feature_product ? false: true || row.feature_product ? true: false}>
{`${row.feature_product ? false: true}` || `${row.feature_product ? true: false}`}
</option>
</select>