javascript – 如何有条件地包装一个React组件?

前端之家收集整理的这篇文章主要介绍了javascript – 如何有条件地包装一个React组件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个组件,有时需要被渲染为一个锚点,其他时候作为一个简单的div.这个prop.url道具,我触发了确定哪个是必需的.如果存在,我需要使用href = {this.props.url}将组件包装在锚点中.否则它只是被渲染为< div />.

可能?

这是我现在正在做的,但感觉可以简化:

  1. if (this.props.link) {
  2. return (
  3. <a href={this.props.link} className={baseClasses}>
  4. <i className={styles.Icon}>
  5. {this.props.count}
  6. </i>
  7. </a>
  8. );
  9. }
  10.  
  11. return (
  12. <i className={styles.Icon}>
  13. {this.props.count}
  14. </i>
  15. );

更新:

这是最后的锁定.感谢提示,@Sulthan

  1. import React,{ Component,PropTypes } from 'react';
  2. import classNames from 'classnames';
  3.  
  4. export default class CommentCount extends Component {
  5.  
  6. static propTypes = {
  7. count: PropTypes.number.isrequired,link: PropTypes.string,className: PropTypes.string
  8. }
  9.  
  10. render() {
  11. const styles = require('./CommentCount.css');
  12. const {link,className,count} = this.props;
  13.  
  14. const iconClasses = classNames({
  15. [styles.Icon]: true,[className]: !link && className
  16. });
  17.  
  18. const Icon = (
  19. <i className={iconClasses}>
  20. {count}
  21. </i>
  22. );
  23.  
  24. if (link) {
  25. const baseClasses = classNames({
  26. [styles.Base]: true,[className]: className
  27. });
  28.  
  29. return (
  30. <a href={link} className={baseClasses}>
  31. {Icon}
  32. </a>
  33. );
  34. }
  35.  
  36. return Icon;
  37. }
  38. }

解决方法

只需使用一个变量.
  1. var component = (
  2. <i className={styles.Icon}>
  3. {this.props.count}
  4. </i>
  5. );
  6.  
  7. if (this.props.link) {
  8. return (
  9. <a href={this.props.link} className={baseClasses}>
  10. {component}
  11. </a>
  12. );
  13. }
  14.  
  15. return component;

或者,您可以使用帮助函数来呈现内容. JSX是像任何其他代码.如果要减少重复,请使用函数和变量.

猜你在找的JavaScript相关文章