我有一个用例,我有一个Image组件,它具有必需的“src”属性和一个可选的“link”属性,如下所示:
var Image = React.createClass({
propTypes: {
link: React.PropTypes.string,
event: React.PropTypes.object,
src: React.PropTypes.string.isRequired
},
handleClick: function(event, link) {
analytics.track(event)
.then(function() {
window.location = link;
});
},
render: function() {
return (
<img className='image' src={this.props.src} onClick={this.handleClick.bind(this, this.props.event, this.props.link)} />
);
} });
如果我想在调用Image组件时有选择地包含可选道具,我该如何优雅地做到这一点?我最初的想法是做这样的三元表达式,除了这不是有效的JSX:
render: function() {
return (
<Image src={this.props.src} {this.props.link.hasOwnProperty('value') ? link=this.props.link.value : ''} />
)
}
在上面的示例中,“this.props.link”是一个对象,可能包含也可能不包含名为“value”的属性,该属性包括单击Image时要浏览的超链接。此外,如果没有link.value存在,我宁愿简单地将它完全放弃,而不是简单地提供一个空字符串作为“链接”道具的值。
我的理由是,在Image组件上我可以添加css“img:hover {cursor:pointer;}”,只有当img实际链接到某处时,而不是全局设置它违反我的应用程序的UX规则。
我知道我可以简单地在三元组中呈现“链接”道具,如果它存在则包含链接的值,如果不存在则为空字符串,但为了好奇,我想看看是否还有另一个实现这一目标的方法。
我还想避免必须做一堆条件语句,这些语句创建了许多冗余的JSX代码,如下所示:
render: function() {
if (this.props.link.hasOwnProperty('value')) {
return <Image link={this.props.link.value} src={this.props.src.value} />;
} else {
return <Image src={this.props.src.value} />;
}
.... // other optional properties
}
想象一下,如果你有很多可选的道具可以让你失去怎样的失控...
你似乎在思考它。
<Image src={this.props.src} link={this.props.link.value} />
在您的组件中,您通常应将任何虚假值视为省略。
if (this.props.link) {
...
}
一个例外是数字,或罕见(并且最好避免的情况),它是一个布尔默认为true。
更直接的答案是使用传播(新的0.12)。
var props = {src: this.props.src};
if (this.props.link.hasOwnProperty('value')) {
props.link = this.props.link.value;
}
<Image {...props} />
要么
var extraProps = {};
if (this.props.link.hasOwnProperty('value')) {
extraProps.link = this.props.link.value;
}
<Image src={this.props.src} {...extraProps} />