如何在反应原生中获得元素的宽度?

木士羽*_*木士羽 11 react-native

如何获得一个元素的宽度作为反应原生如View?由于反应原生的宽度没有百分比用量,如何获得元素或父元素的宽度?

Nad*_*bit 14

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

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

<View onLayout={(event) => this.measureView(event)}>
Run Code Online (Sandbox Code Playgroud)

就宽度和高度百分比而言,您可以获得窗口宽度和高度,并使用它们:

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,
Run Code Online (Sandbox Code Playgroud)

  • 请注意,`onLayout` 事件将在 ** 组件渲染后触发。因此,如果您想要不重新渲染的 chlld 组件的百分比宽度,我可以建议使用 [here](https://github.com/vitalets/react-native-extended-stylesheet#percents) 中描述的变量 (2认同)