【发布时间】:2015-11-14 16:48:49
【问题描述】:
我有一个组件,有时需要呈现为<anchor>,有时需要呈现为<div>。我读到的prop 是this.props.url。
如果存在,我需要渲染包装在<a href={this.props.url}> 中的组件。否则它只会被渲染为<div/>。
可能吗?
这就是我现在正在做的事情,但觉得可以简化:
if (this.props.link) {
return (
<a href={this.props.link}>
<i>
{this.props.count}
</i>
</a>
);
}
return (
<i className={styles.Icon}>
{this.props.count}
</i>
);
更新:
这是最后的锁定。感谢您的提示,@Sulthan!
import React, { Component, PropTypes } from 'react';
import classNames from 'classnames';
export default class CommentCount extends Component {
static propTypes = {
count: PropTypes.number.isRequired,
link: PropTypes.string,
className: PropTypes.string
}
render() {
const styles = require('./CommentCount.css');
const {link, className, count} = this.props;
const iconClasses = classNames({
[styles.Icon]: true,
[className]: !link && className
});
const Icon = (
<i className={iconClasses}>
{count}
</i>
);
if (link) {
const baseClasses = classNames({
[styles.Base]: true,
[className]: className
});
return (
<a href={link} className={baseClasses}>
{Icon}
</a>
);
}
return Icon;
}
}
【问题讨论】:
-
您也可以将
const baseClasses =移动到该if (this.props.link)分支中。由于您使用的是 ES6,因此您也可以通过const {link, className} = this.props;简化一点,然后使用link和className作为局部变量。 -
伙计,我喜欢它。越来越多地了解 ES6,它总是会提高可读性。感谢您的额外提示!
-
什么是“最终锁定”?
标签: javascript reactjs