You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React条件渲染图片/视频异常:仅显示图片问题求助

问题分析与解决方案

你的核心问题是图片字段始终带有默认值,导致条件判断image ? ... : ...永远成立,视频对应的else分支根本不会执行。因为不管用户有没有上传图片,image都是有效的默认图片URL,所以条件永远为true,只会显示图片。

解决思路1:增加媒体类型标识(推荐)

在表单提交时,额外传递一个mediaType字段(值为'image'或'video'),直接根据这个字段判断要渲染的内容,彻底摆脱对默认值的依赖:

const Post = (props) => {
  const {
    id,
    owner,
    profile_id,
    profile_image,
    title,
    content,
    image,
    video,
    updated_on,
    postPage,
    mediaType, // 新增:标记当前是图片还是视频
  } = props;

  return (
    <Card className={styles.Post}>
      <Card.Body>
        <Media className="align-items-center justify-content-between">
          <Link to={`/profiles/${profile_id}`}>
            <Avatar src={profile_image} height={55} /> {owner}
          </Link>
          <div className="d-flex align-items-center">
            <span>
              {updated_on}
              {is_owner && postPage && "..."}
            </span>
          </div>
        </Media>
      </Card.Body>
      <div>
        {mediaType === 'image' ? (
          <Link to={`/posts/${id}`}>
            <Card.Img src={image} alt={title} />                       
          </Link>
        ) : (
          <Link to={`/posts/${id}`}>
            <video src={video} width={400} height={400} controls /> 
          </Link>
        )}
      </div>
    </Card>
  );
};

解决思路2:判断是否为默认图片

如果没法新增字段,就直接判断image是否等于默认图片的URL,只有当是用户上传的真实图片时才显示图片,否则显示视频:

// 替换成你实际使用的默认图片URL
const DEFAULT_IMAGE = '/assets/default-post-image.png';

const Post = (props) => {
  const {
    id,
    owner,
    profile_id,
    profile_image,
    title,
    content,
    image,
    video,
    updated_on,
    postPage,
  } = props;

  return (
    <Card className={styles.Post}>
      <Card.Body>
        <Media className="align-items-center justify-content-between">
          <Link to={`/profiles/${profile_id}`}>
            <Avatar src={profile_image} height={55} /> {owner}
          </Link>
          <div className="d-flex align-items-center">
            <span>
              {updated_on}
              {is_owner && postPage && "..."}
            </span>
          </div>
        </Media>
      </Card.Body>
      <div>
        {image !== DEFAULT_IMAGE ? (
          <Link to={`/posts/${id}`}>
            <Card.Img src={image} alt={title} />                       
          </Link>
        ) : (
          <Link to={`/posts/${id}`}>
            <video src={video} width={400} height={400} controls /> 
          </Link>
        )}
      </div>
    </Card>
  );
};

注意:思路2的局限性在于如果默认图片有多个版本、动态地址(比如带CDN参数),判断会失效,所以优先用思路1。

内容的提问来源于stack exchange,提问作者Sara Bojorge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 19:05:12