即使子组件位置是绝对的,图像组件也不能包含子组件

Posted

技术标签:

【中文标题】即使子组件位置是绝对的,图像组件也不能包含子组件【英文标题】:Image component cannot contain child even when child component position is absolute 【发布时间】:2018-01-08 06:47:29 【问题描述】:

我正在尝试在 Image 上显示登录表单。我确实将子位置设为Absolute,但仍然出现以下错误:

图像 组件不能包含子组件。如果你想渲染 图像顶部的内容,请考虑使用绝对定位。

下面是我的Login.js:

import React, Component from 'react';
import Text, View, StyleSheet, Image from 'react-native';
import firebase from 'firebase';

export default class Login extends Component<>

  render ()
    return (
      <View style=styles.container>
        <Image source=require('../resources/images/background_image.png') style=styles.backgroundImage >
            <View style=styles.loginContainer>
            </View>
        </Image>
      </View>
    );
  



const styles = StyleSheet.create(
  container: 
    flex: 1,
  ,
  backgroundImage: 
    flex: 1,
    resizeMode: 'cover',
  ,
  loginContainer: 
    position: 'absolute',
   top: 0,
   bottom: 0,
   left: 0,
   right: 0
  ,
);

谁能告诉我我做错了什么?

【问题讨论】:

可能是因为命名约定?您可以将您的组件命名为 Image 以外的其他名称吗?也许叫你组件 ImgComp 什么的 因为 html 已经有一个名为 Image 的标签,它可能会导致问题 错误很清楚:不能包含子项。这意味着您不能将 View 设置为 Image 的子级。 只需将View 标签放在Image 标签下方即可。这意味着Image 和子View 都是***View 的子级 @Khoa 不起作用我之前尝试过 【参考方案1】:

为此使用 ImageBackground 组件 - 只需像导入图像一样从“react-native”导入它。

它需要孩子 - 所以你会这样使用它:

<ImageBackground source= Img >
    <Text>Hello</Text>
</ImageBackground>

超级有用,但很难找到。

【讨论】:

【参考方案2】:

因为你带来了官方评论。

Image 组件不能包含子组件。如果你想渲染 图像顶部的内容,请考虑使用绝对定位。

图片不能包含孩子。 (以前可以,现在不行了)

评论说“使用绝对定位”并不意味着如果你使用绝对定位就可以包含孩子。

这意味着您必须将另一个视图的样式设置为绝对样式并将其放在您的图像上方。

【讨论】:

尝试将***视图设为绝对视图,但仍然无法正常工作 不,您应该将“孩子”视图设为绝对视图。 虽然,就像@dan674 回答的那样,如果你想在 Image 中包含孩子,你可以使用 ImageBackground。【参考方案3】:

正如错误提示,在您要放置在图像上方的项目上使用position: absolute

我的例子是 HTML,但应该是类似的。

figure 
  position: relative;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .1);
  display: inline-block;


img 
  vertical-align: middle;


figcaption 
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, .1);
  padding: 5px 10px;
<figure>
  <img src="http://via.placeholder.com/350x150" />
  <figcaption>Img caption</figcaption>
</figure>

【讨论】:

正如您在我的代码片段中看到的那样,我希望在图像上方查看(登录容器),并将其标记为绝对 我认为绝对位置元素应该是图片的兄弟标题。 不,它不一定是标题

以上是关于即使子组件位置是绝对的,图像组件也不能包含子组件的主要内容,如果未能解决你的问题,请参考以下文章

Flutter Widget - Stack and Positioned 层叠绝对定位

Vue通用组件的封装

父子组件间的传值

Flutter控件——布局控件:层叠

React 啥时候重新渲染子组件?

浅析Vue中的 .sync 修饰符