最佳答案
我有一个组件,有时需要作为一个 <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;
}
}