如何有条件地包装 React 组件?
2022-08-30 04:41:01
我有一个组件,有时需要将其呈现为 a,有时需要将其呈现为 .我读到来确定这一点,是.<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;
}
}