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

React使用useRef操作样式报错Cannot read 'style' of undefined如何解决

报错原因及修复方案

核心问题:自定义组件未透传ref导致ref.current为空

你给<Card.List>自定义组件直接绑定ref时,React默认不会将ref透传给组件内部的真实DOM节点,因此listRef.current的值为undefined,读取style属性就会抛出你遇到的类型错误。
修复方式:修改Card组件中Card.List的定义,使用React.forwardRef接收外部传入的ref,并挂载到真实的List DOM元素上:

// 修改Card组件代码中的Card.List部分
Card.List = React.forwardRef(function CardList({children,...restProps}, ref) {
     return <List ref={ref} {...restProps} >{children}</List>
})

次要问题:transform属性值格式错误

你当前写的translate(230)缺少单位,就算拿到DOM也不会生效,需要补充px单位,且横向滑动建议用更明确的translateX,同时添加非空判断避免偶发报错:

// 修改业务代码中的handleClick逻辑
const handleClick=(direction)=> {
    if(!listRef.current) return
    if(direction==="left") {
         listRef.current.style.transform = `translateX(230px)`
    } else {
         listRef.current.style.transform = `translateX(-230px)`
    }
}

可选优化

可以给List的样式添加过渡属性,让滑动效果更流畅:

/* 在styles/card文件的List样式规则中添加 */
transition: all 0.3s ease;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 03:36:03