我想在按钮元素上动态包含/省略 disabled 属性。我见过很多动态属性值的例子,但不是属性本身。我有以下渲染功能:
render: function() {
var maybeDisabled = AppStore.cartIsEmpty() ? "disabled" : "";
return <button {maybeDisabled}>Clear cart</button>
}
由于“{”字符,这会引发解析错误。如何根据 AppStore.cartIsEmpty() 的(布尔)结果包含/省略 disabled 属性?
原文由 Timmy 发布,翻译遵循 CC BY-SA 4.0 许可协议
添加可选属性(包括
disabled
以及您可能想要使用的其他属性)的最简洁方法目前是使用 JSX 传播属性:通过使用扩展属性,您可以使用 javascript 对象实例动态添加(或覆盖)您想要的任何属性。 In my example above, the code creates a
disabled
key (with adisabled
value in this case) when thedisabled
property is passed to theHello
组件实例。但是,如果您只想使用
disabled
, 则此 答案效果很好。