如何在react native中获取元素的宽度?

bwitn5fc  于 2023-10-22  发布在  React
关注(0)|答案(1)|浏览(141)

如何在react native(如View)中获取元素的宽度?由于react native中没有width的百分比使用率,如何获取元素或父元素的宽度?

bweufnob

bweufnob1#

您可以调用onLayout事件来测量元素:

measureView(event) {
  console.log('event properties: ', event);
  console.log('width: ', event.nativeEvent.layout.width)
}

<View onLayout={(event) => this.measureView(event)}>

至于宽度和高度的百分比,你可以得到窗口的宽度和高度,并像这样使用它们:

const {
    ...
    Dimensions
} = React

const width = Dimensions.get('window').width
const height = Dimensions.get('window').height

// 80% width
width: width * .8,

// 25% height
height: height / 4,

相关问题