获取弹性组件的大小

问题描述 投票:0回答:1

我有两个组件,一个

Parent
和一个
Child
。后者应该有
flex
布局,这样它就占据了 75% 的垂直空间:

const Parent: FC<PropsWithChildren> = (props) => {
    return (<View style={ styles.container }><MyChild /></View>)
}
const Child: FC<PropsWithChildren> = (props) => {
    return (<View style={ styles.childSytle }/>)
}

const styles = StyleSheet.create({
    container: { 
        flex: 1,
        flexdirection: 'column'
    },
    childStyle: { flex: 9 }
});

我现在想要实现的是从

Child
中获取我的
Parent
组件的实际大小。当组件为
flex
时,是否可以获得组件的大小?

我已经为我的

forwardref
尝试过
Child
以获得对
Child
的参考。但是我不知道如何获得它的大小。

react-native flexbox
1个回答
0
投票
function Parent() {
 return (
  //...
  <View>
   onLayout={event=>{
    const { width, height } = event.nativeEvent.layout
   }}
   <Child/>
  </View>
  //...
 )

您可以通过在子组件的包装组件上实现 onLayout 属性来检索实际的组件宽度和高度。然后您应该根据用例将它们保存为状态或引用变量。

© www.soinside.com 2019 - 2024. All rights reserved.