ReactJS 中的动态属性 [英] Dynamic attribute in ReactJS
问题描述
我想动态地包含/省略按钮元素上的 disabled 属性.我见过很多动态属性值的例子,但没有看到属性本身.我有以下渲染功能:
I want to dynamically include/omit the disabled attribute on a button element. I have seen plenty of examples of dynamic attribute values, but not of attributes themselves. I have the following render function:
render: function() {
var maybeDisabled = AppStore.cartIsEmpty() ? "disabled" : "";
return <button {maybeDisabled}>Clear cart</button>
}
由于{"字符,这会引发解析错误.如何根据 AppStore.cartIsEmpty() 的(布尔值)结果包含/省略 disabled 属性?
This throws a parse error because of the "{" character. How can I include/omit the disabled attribute based on the (boolean) result of AppStore.cartIsEmpty()?
推荐答案
添加可选属性(包括 disabled
和您可能想要使用的其他属性)的最简洁方法目前是使用 JSX 传播属性:
The cleanest way to add optional attributes (including disabled
and others you might want to use) is currently to use JSX spread attributes:
var Hello = React.createClass({
render: function() {
var opts = {};
if (this.props.disabled) {
opts['disabled'] = 'disabled';
}
return <button {...opts}>Hello {this.props.name}</button>;
}
});
React.render((<div><Hello name="Disabled" disabled='true' />
<Hello name="Enabled" />
</div>)
, document.getElementById('container'));
通过使用扩展属性,您可以使用 javascript 对象实例动态添加(或覆盖)您想要的任何属性.在我上面的示例中,当将 disabled
属性传递给 disabled
属性时,代码会创建一个 disabled
键(在本例中为 disabled
值)code>Hello 组件实例.
If you only want to use disabled
though, this answer works well.
这篇关于ReactJS 中的动态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!