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

React开发中如何将<View>的宽高传递给子Child组件

问题原因

你当前的写法存在两个核心问题:

  • width和height是在onLayout的回调函数内部通过let声明的,属于函数块级作用域,回调外部的JSX代码没有访问权限,因此会报变量未定义。
  • onLayout是View组件渲染完成后才会触发的异步回调,组件初次渲染时还未拿到宽高数值,需要用响应式状态存储该值,触发组件重渲染后才能将数值传递给子组件。

解决方法

使用useState存储宽高数值即可,示例代码如下:

import { useState } from 'react';
import { View } from 'react-native';

// 你的父组件内部逻辑
const ParentComponent = () => {
  // 初始化宽高状态,默认值可根据业务需求调整
  const [layoutSize, setLayoutSize] = useState({ width: 0, height: 0 });

  return (
    <View 
      onLayout={(event) => {
        const { width, height } = event.nativeEvent.layout;
        setLayoutSize({ width, height });
      }} 
    >
      <Child width={layoutSize.width} height={layoutSize.height} />
    </View>
  )
}

可选优化

如果不希望子组件在首次渲染时拿到初始的0值,可以增加渲染判断,等拿到真实尺寸后再渲染子组件:

<View 
  onLayout={(event) => {
    const { width, height } = event.nativeEvent.layout;
    setLayoutSize({ width, height });
  }} 
>
  {layoutSize.width > 0 && <Child width={layoutSize.width} height={layoutSize.height} />}
</View>

如果你使用的是类组件,将宽高值存在组件state中,调用setState更新即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 21:24:05