react-native:相对于设备而不是父元素定位子元素

ren*_*dom 5 react-native

<Child />里面有一个子元素,<Parent height="40"/>我想相对于设备视图区域而不是父元素绝对定位子元素。

示例布局

<device height="1000">

 <header height="500">
 <ScrollView />
 <parent height=40">
  <child height="300" top="150" />
 </parent>


</device>
Run Code Online (Sandbox Code Playgroud)

position="absolute" 是相对于父母的,没有 position="fixed"

Muh*_*man 8

relative :相对于\xe2\x80\x99的当前位置,但可以移动。或者一个相对定位的元素是相对于它本身定位的。

\n

Absolute :在 React Native 中,ABSOLUTE 定位的元素是相对于它最近的父级定位的。如果该父级恰好是一个覆盖设备整个视口的盒子,那么它的工作方式就像固定的(子级可以相对于设备定位)。文档中有更好的解释

\n

官方文档建议的内容(见上面的链接):如果您想相对于不是其父级的东西定位子级[在您的情况下它将是设备视口],请不要使用样式。使用组件树。为此,请参阅解决方案#2。

\n

解决方案一:

\n

这是一个演示:https://snack.expo.io/@nomi9995/7ee9c4

\n

您可以使用react-native-paper中的门户来定位来自设备而不是来自父级的子组件

\n
import * as React from "react";\nimport { View, StyleSheet } from "react-native";\nimport { Portal, Text, Provider as PaperProvider } from "react-native-paper";\n\nconst Child=()=>{\nreturn (\n  <Text>This is Child component which take positioned from Parent</Text>\n    )\n}\nclass App extends React.Component {\n  render() {\n    return (\n      <View style={{ flex: 1 }}>\n        <View style={styles.container}>\n          <Portal>\n            <Child />\n          </Portal>\n        </View>\n      </View>\n    );\n  }\n  \xc3\x8e;\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    justifyContent: "center",\n    alignItems: "center",\n    flex: 1,\n    backgroundColor: "#eee",\n  },\n});\n\nconst JSX = () => {\n  return (\n    <PaperProvider>\n      <App />\n    </PaperProvider>\n  );\n};\n\nexport default JSX;\n\n
Run Code Online (Sandbox Code Playgroud)\n

解决方案2:

\n

将子级放在父级之外并给出位置:“绝对”

\n

像这样

\n
<device height="1000">\n\n <header height="500">\n <ScrollView />\n <parent height=40">\n </parent>\n\n <child height="300" style={{position:"absolute",top:150}} />\n\n</device>\n
Run Code Online (Sandbox Code Playgroud)\n

  • 我知道这有效。但是,如果您在某些时候有深层嵌套的组件,很难将组件放回根树怎么办? (2认同)