根据孩子的尺寸设置父母的身高和宽度

时间:2019-07-14 11:23:47

标签: typescript react-native layout

我需要根据他的孩子的身高和宽度设置一个View的高度和宽度。有可能吗?

我尝试使用onLayout道具,但实际上我没有获得使用它的正确方法。另外,我尝试使用测量方法,但现在在本机0.59上不推荐使用ref。

import React, {Component} from 'react';
import {View, Text} from 'react-native'

export default class myClass extends Component{
    render(){
        return(
            <View style={styles.container}>
               <View style={{}}>   //HERE I WANNA SET width and height of his child
                 <View>
                   <Text>Hello<Text>
                   <Text>Hello<Text>
                   <Text>Hello<Text>
                 </View>
               </View>
            </View>
        )
    }

}

1 个答案:

答案 0 :(得分:0)

如果您使用带有钩子的React(版本16.8及更高版本),这通常通过使用钩子来完成。首先创建如下的useLayoutDimension钩子:

import { useState, useCallback } from 'react'

export function useLayoutDimension() {
  const [dimension, setDimension] = useState(0)
  const layoutDimension = { width: 0, height: 0 }
  const onLayout = useCallback(({ nativeEvent }) => {
    layoutDimension.width = nativeEvent.layout.width
    layoutDimension.height = nativeEvent.layout.height
    if (dimension !== layoutDimension.width && layoutDimension.width > 0) {
      setDimension(layoutDimension)
    }
  }, [])

  return {
    dimension,
    onLayout,
  }
}

然后在 Child 组件中执行以下操作:

import { useLayoutDimension } from 'app/hooks'

export const ChildComponent = (props) => {
  const { dimension, onLayout } = useLayoutDimension()

  useEffect(
    () => {
      props.getChildDimensions(dimension)
    },
    [dimension]
  )

  return (
    <View style={styles.ShadowWrapper} onLayout={onLayout}>
        {...content}
    </View>
  )
}

然后在父级组件中为这样的维度设置状态的一部分:

//...rest of the parent component
//Child below
<ChildComponent
    getChildDimensions={(dimensions) => {
        this.setState({
            dimensions: dimensions,
        })
    }}
/>

然后您可以将父组件中的任何其他组件设置为尺寸状态

<View style={{width: this.state.dimension.width, height: this.state.dimension.height}}

注意:这是使用类和功能组件的组合(子级是函数级,父级是类)。如果您对这些概念不满意,this会有所帮助。 useState是使用this.state的挂钩方法,useEffect是在特定状态更改时触发的挂钩。如果您不熟悉此内容,则对hooks进行简短的阅读将对您大有帮助。

PS::第一个渲染将没有尺寸,因为需要设置状态。但是,这通常并不明显。