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

首次在React.js中使用styled-components遇state传递错误求助

解决styled-components中Cannot read property 'x' of undefined的问题

嘿,刚上手styled-components就遇到这个小坑很正常,咱们一步步捋清楚问题在哪:

首先看你styles.js里的代码,有个明显的语法错误:top属性的动态值写法错了,你用了普通大括号{state.pos.y},但styled-components读取组件props必须用${}包裹函数才行。

第一步:修复styles.js里的语法问题

把你的StyledPopopDiv代码改成这样:

export const StyledPopopDiv = styled.div` 
  width: 200px; 
  height: 100px; 
  background: #cecece; 
  position: fixed; 
  z-index: 200; 
  left: ${state => state.pos.x}px; 
  top: ${state => state.pos.y}px; 
`;
StyledPopopDiv.displayName = 'StyledPopopDiv';

重点看top那行,我把{state.pos.y}改成了${state => state.pos.y},这是styled-components读取传入props的正确语法。

第二步:确保在Abc.js中正确传递pos属性

接下来要确认你在使用StyledPopopDiv组件时,确实把pos属性传进去了,而且pos是包含x和y的对象:

  • 如果是类组件:
import { StyledPopopDiv } from './styles';

class Abc extends React.Component {
  state = {
    pos: { x: 100, y: 100 } // 确保pos是有x、y属性的对象
  };

  render() {
    return <StyledPopopDiv pos={this.state.pos} />;
  }
}
  • 如果是函数组件(React Hooks):
import { useState } from 'react';
import { StyledPopopDiv } from './styles';

const Abc = () => {
  const [pos, setPos] = useState({ x: 100, y: 100 });

  return <StyledPopopDiv pos={pos} />;
};

第三步:添加容错处理(可选但推荐)

为了避免pos可能为undefined的极端情况,你可以给x和y加个默认值,这样即使pos没传也不会报错:

left: ${state => state.pos?.x || 0}px; 
top: ${state => state.pos?.y || 0}px; 

这里用了可选链操作符?.,如果pos是undefined,就会用后面的0作为默认值,代码会更健壮。

这样改完之后,应该就能解决你遇到的Cannot read property 'x' of undefined错误啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:09:27