无法在 JSX 中渲染布尔值?
Cannot render boolean value in 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>
编辑: 这是示例的 JSBin link http://jsbin.com/nibihodoce/1/edit?html,js,output
编辑 2: 我已经探索了 .toString() 替代方案,但是因为我正在遍历对象数组并且该对象的特定字段可以有 string/integer/boolean 种价值。将 .toString() 应用于所有“它们”似乎并不是最佳选择。
您可以将布尔值转换为字符串,并将其与空字符串连接:
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')
);
如果你的变量不能有布尔值,你应该把它转换成布尔值:
// `ipsumText` variable is `true` now.
var ipsumText = !!'text';
Boolean Value: { ipsumText.toString() }
或
Boolean Value: { String(ipsumText) }
或
Boolean Value: { '' + ipsumText }
或
{`Boolean Value: ${ipsumText}`}
或
Boolean Value: { JSON.stringify(ipsumText) }
我更喜欢第二种选择。通用、快速、适用于所有原始类型: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>
我正在尝试在 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>
编辑: 这是示例的 JSBin link http://jsbin.com/nibihodoce/1/edit?html,js,output
编辑 2: 我已经探索了 .toString() 替代方案,但是因为我正在遍历对象数组并且该对象的特定字段可以有 string/integer/boolean 种价值。将 .toString() 应用于所有“它们”似乎并不是最佳选择。
您可以将布尔值转换为字符串,并将其与空字符串连接:
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')
);
如果你的变量不能有布尔值,你应该把它转换成布尔值:
// `ipsumText` variable is `true` now.
var ipsumText = !!'text';
Boolean Value: { ipsumText.toString() }
或
Boolean Value: { String(ipsumText) }
或
Boolean Value: { '' + ipsumText }
或
{`Boolean Value: ${ipsumText}`}
或
Boolean Value: { JSON.stringify(ipsumText) }
我更喜欢第二种选择。通用、快速、适用于所有原始类型: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>