我有一个组件,有时需要被渲染为一个锚点,其他时候作为一个简单的div.这个prop.url道具,我触发了确定哪个是必需的.如果存在,我需要使用href = {this.props.url}将组件包装在锚点中.否则它只是被渲染为< div />.
可能?
这是我现在正在做的,但感觉可以简化:
- if (this.props.link) {
- return (
- <a href={this.props.link} className={baseClasses}>
- <i className={styles.Icon}>
- {this.props.count}
- </i>
- </a>
- );
- }
- return (
- <i className={styles.Icon}>
- {this.props.count}
- </i>
- );
更新:
- 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;
- }
- }