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

React Native:传递screenWidth给子组件在styled components中报错求助

React Native Styled Components 屏幕宽度使用问题解决

错误原因及修复方案

1. 移除多余的px单位

React Native样式默认使用dp作为单位,不需要手动添加px,这是你前两种写法报错的核心原因。调整styled组件的写法:

// 子组件中正确接收props并设置宽度
const CardContainer = styled.View`
  width: ${props => props.screenWidth};
`;

const BankAccountInfoCard = ({ screenWidth }) => {
  return (
    <CardContainer screenWidth={screenWidth}>
      {/* 卡片内容 */}
    </CardContainer>
  );
};

2. 修正直接调用Dimensions的问题

直接在styled模板字符串里调用Dimensions.get('window').width,会导致初始化后无法响应屏幕旋转,且可能因时机问题报错。改为在组件内部获取并监听变化:

import { Dimensions, useState, useEffect } from 'react-native';
import styled from 'styled-components/native';

const CardContainer = styled.View`
  width: ${props => props.screenWidth};
`;

const BankAccountInfoCard = () => {
  const [screenWidth, setScreenWidth] = useState(Dimensions.get('window').width);

  useEffect(() => {
    const updateWidth = () => setScreenWidth(Dimensions.get('window').width);
    Dimensions.addEventListener('change', updateWidth);
    return () => Dimensions.removeEventListener('change', updateWidth);
  }, []);

  return <CardContainer screenWidth={screenWidth}>{/* 内容 */}</CardContainer>;
};

3. 检查父组件props传递正确性

确保父组件传递的props名称与子组件接收的完全一致:

// 父组件代码
import { Dimensions } from 'react-native';
import BankAccountInfoCard from './BankAccountInfoCard';

const ParentComponent = () => {
  const { width: screenWidth } = Dimensions.get('window');

  return (
    <View>
      <BankAccountInfoCard screenWidth={screenWidth} />
    </View>
  );
};

关键提示

  • React Native样式不识别px单位,直接使用数值即可对应dp单位。
  • 若需适配屏幕旋转,必须通过Dimensions.addEventListener监听宽度变化,避免布局异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 04:15:00