代码之家  ›  专栏  ›  技术社区  ›  rendom

反应本机:相对于设备而不是父元素定位子元素

  •  0
  • rendom  · 技术社区  · 7 年前

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

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

    position="absolute" 是相对于父项的,并且没有 position="fixed"

    0 回复  |  直到 7 年前
        1
  •  4
  •   jaquinocode    5 年前

    相对: 相对于其当前位置,但可以移动。或者相对定位的元素相对于自身定位。

    绝对的: 在React Native中,绝对定位元素相对于其最近的父元素进行定位。如果父对象恰好是一个覆盖设备整个视口的框,那么它的工作方式就像固定的(子对象可以相对于设备进行定位)。 Better explanation here from the docs

    官方文档的建议(见上面的链接):如果你想相对于不是其父对象的对象定位子对象(在你的情况下是设备视口),不要使用样式。使用组件树。关于这一点,请参见解决方案#2。

    解决方案1:

    https://snack.expo.io/@nomi9995/7ee9c4

    Portal 从…起 react-native-paper 从设备而不是父设备定位子组件

    import * as React from "react";
    import { View, StyleSheet } from "react-native";
    import { Portal, Text, Provider as PaperProvider } from "react-native-paper";
    
    const Child=()=>{
    return (
      <Text>This is Child component which take positioned from Parent</Text>
        )
    }
    class App extends React.Component {
      render() {
        return (
          <View style={{ flex: 1 }}>
            <View style={styles.container}>
              <Portal>
                <Child />
              </Portal>
            </View>
          </View>
        );
      }
      Î;
    }
    
    const styles = StyleSheet.create({
      container: {
        justifyContent: "center",
        alignItems: "center",
        flex: 1,
        backgroundColor: "#eee",
      },
    });
    
    const JSX = () => {
      return (
        <PaperProvider>
          <App />
        </PaperProvider>
      );
    };
    
    export default JSX;
    
    

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

    <device height="1000">
    
     <header height="500">
     <ScrollView />
     <parent height=40">
     </parent>
    
     <child height="300" style={{position:"absolute",top:150}} />
    
    </device>
    
    推荐文章