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

React函数组件访问props.deviceType触发TypeError错误求助

修复React函数组件中TypeError: Cannot read properties of undefined (reading 'props')错误

错误原因

你写的是函数组件,函数组件里不存在this(this为undefined),所以不能用this.props来获取父组件传入的属性。函数组件的props是直接作为函数参数传入的,直接用参数名访问即可。

修复步骤&代码

直接用参数props替代this.props,还可以通过解构赋值简化代码,同时补充完整responsive配置(react-multi-carousel需要这个属性来实现响应式布局):

import React from "react";
import PastEventCard from "./PastEventCard";
import Carousel from "react-multi-carousel";
import "react-multi-carousel/lib/styles.css";

function PastEventSection(props) {
  // 解构取出deviceType,简化后续代码
  const { deviceType } = props;

  // 配置不同设备下的轮播项数量,可根据需求调整
  const responsive = {
    desktop: {
      breakpoint: { max: 3000, min: 1024 },
      items: 3
    },
    tablet: {
      breakpoint: { max: 1024, min: 464 },
      items: 2
    },
    mobile: {
      breakpoint: { max: 464, min: 0 },
      items: 1
    }
  };

  return (
    <Carousel
      autoPlay={deviceType !== "mobile"}
      centerMode={deviceType !== "mobile"}
      removeArrowOnDeviceType={["tablet", "mobile"]}
      deviceType={deviceType}
      responsive={responsive}
    >
      <PastEventCard title="" description="" imgURL="" />
      <PastEventCard title="" description="" imgURL="" />
      <PastEventCard title="" description="" imgURL="" />
    </Carousel>
  );
}

export default PastEventSection;

关键修改说明

  • 删除所有this.props,改用props.deviceType,或者解构后直接用deviceType
  • 简化布尔判断:deviceType !== "mobile"本身就是布尔值,无需额外写? true : false
  • 补充完整responsive对象,并传入Carousel组件,否则轮播可能无法正常适配不同设备
  • 移除了代码中未使用的useState和Link导入,减少冗余

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 04:45:37