Mam komponent, który czasami trzeba będzie renderować jako plik, <anchor>a innym razem jako plik <div>. propCzytam w celu ustalenia tego jest this.props.url.
Jeśli istnieje, muszę wyrenderować komponent opakowany w plik <a href={this.props.url}>. W przeciwnym razie zostanie po prostu renderowany jako plik <div/>.
Możliwy?
Oto, co teraz robię, ale czuję, że można to uprościć:
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>
);
AKTUALIZACJA:
Oto ostateczne zamknięcie. Dzięki za wskazówkę, @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 =do tejif (this.props.link)gałęzi. Ponieważ używasz ES6, możesz także nieco uprościć,const {link, className} = this.props;używająclinkiclassNamejako zmiennych lokalnych.