我试图在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>
编辑:以下是示例http://jsbin.com/nibihodoce/1/edit?html,js,output
的JSBin链接编辑2:我已经探索过.toString()替代方法,但是因为我正在迭代一个对象数组,并且该对象的特定字段可以具有字符串/整数/布尔类型值。将.toString()应用于所有'em'似乎不是最佳的。
答案 0 :(得分:60)
Boolean Value: { ipsumText.toString() }
UPD:或
Boolean Value: { String( ipsumText ) }
或
Boolean Value: { '' + ipsumText }
或
{`Boolean Value: ${ipsumText}`}
或
Boolean Value: { JSON.stringify( ipsumText ) }
我更喜欢第二种选择。通用,快速,适用于所有原始类型:Boolean( smth )
,Number( smth )
。
答案 1 :(得分:1)
您可以将布尔值转换为字符串,并将其与空字符串连接:
var ipsumText = true;
ReactDOM.render(
<div>
Boolean Value: {ipsumText + ''}
</div>,
document.getElementById('impl')
);
或者,当您将bool
值分配给变量时,您可以这样做:
var ipsumText = true + '';
ReactDOM.render(
<div>
Boolean Value: {ipsumText}
</div>,
document.getElementById('impl')
);
如果您的变量不具有布尔值,则应将其转换为boolean:
// `ipsumText` variable is `true` now.
var ipsumText = !!'text';
答案 2 :(得分:-1)
<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>