仅当道具数据包含特定值时才渲染链接

时间:2019-01-02 22:26:41

标签: javascript reactjs

我正在尝试在About页面上将应聘者姓名链接到简历。但是,有些人没有简历。如果他们的JSON文件中没有填写CV PDF,我想删除a标签/名称上的链接。我知道如何在React之外做到这一点,因为我已经设置了信息,所以我不确定何时将javascript需要放在渲染而不是返回区域中。

import React, { Component } from 'react';
import Image from 'react-image-resizer';
import '../styles/PersonCard.css';


class PersonCard extends Component {

  render() {
    return (
      <div className="card-container">
        <div className="card">
          <div className="side">
            <Image 
              className="card-img-top"
              src={process.env.PUBLIC_URL + "/images/bios/" + this.props.data.img_name}
              height={249}
              width={249} 
            />
          </div>
          <div className="card-body">
            <a href={process.env.PUBLIC_URL + "/pdfs/" + this.props.data.pdf}>
              <h5 className="card-title">
                {this.props.data.name + " " + this.props.data.credentials}
              </h5>
            </a>
            <h6 className="card-text">{this.props.data.position}</h6>
            <p className="card-text">{this.props.data.email}</p>
            <p className="card-text">{this.props.data.phone}</p>
          </div>
        </div>
      </div>
    );
  }
}

export default PersonCard;

P.S。 JSON设置为以下格式:

{
    "name": "John Smith",
    "credentials": "PhD",
    "position": "Professor",
    "email": "jsmith@uni.edu",
    "phone": "123-456-7890",
    "designations": [
        "Faculty"
    ],
    "img_name": "JohnSmith.jpg",
    "pdf": "jSmithCV.pdf"

}

1 个答案:

答案 0 :(得分:0)

我认为最简单的方法是创建一个额外的组件来呈现其子代:

const CVComponent = ({ children, pdf }) => pdf ? (
  <a href={process.env.PUBLIC_URL + "/pdfs/" + pdf}>
    {children}
  </a>
) : <div>{children}</div>;

然后您可以像这样使用它:

class PersonCard extends Component {

  render() {
    return (
      <div className="card-container">
        <div className="card">
          <div className="side">
            <Image 
              className="card-img-top"
              src={process.env.PUBLIC_URL + "/images/bios/" + this.props.data.img_name}
              height={249}
              width={249} 
            />
          </div>
          <div className="card-body">
            <CVComponent pdf={this.props.data.pdf}>
              <h5 className="card-title">
                {this.props.data.name + " " + this.props.data.credentials}
              </h5>
            </CVComponent>
            <h6 className="card-text">{this.props.data.position}</h6>
            <p className="card-text">{this.props.data.email}</p>
            <p className="card-text">{this.props.data.phone}</p>
          </div>
        </div>
      </div>
    );
  }
}