How to get width of an element in react native?

2020-07-03 06:34发布

问题:

How get width of an element in react native such as View ? As there is not percent usage for width in react native, how to get width of an element or parent element?

回答1:

You can call the onLayout event to measure an element:

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

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

As far as percentage width and height, you can get the window width and height and use them like this:

var {
   ...
   Dimensions
} = React

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

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

// 25% height
height: height / 4,