简体   繁体   English

组件仅在其中有项目时才呈现

[英]Component only rendered if there is an item in it

I have a component that is only being rendered if there is Text.我有一个只有在有文本时才会呈现的组件。 I am trying to create a header div to a card div that i created, but the header div isn't being rendered properly.我正在尝试为我创建的卡片 div 创建一个 header div,但是 header div 没有正确呈现。

FeedCardHeader.js FeedCardHeader.js

import React from 'react';
import styled from 'styled-components/native';
import { Text } from 'react-native'

const Root = styled.View`
    height 50;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    background-color: blue;
`;

function FeedCardHeader() {
    return(
        <Root>
            <Text>This is a text</Text>
        </Root>
    )
}

export default FeedCardHeader;

FeedCard.js FeedCard.js

import React from 'react';
import styled from 'styled-components/native';

import FeedCardHeader from './FeedCardHeader';

const Root = styled.View`
  min-height: 180px;
  background-color: white;
  width: 100%;
  shadow-color: ${props => props.theme.SECONDARY};
  shadow-offset: 0px 2px;
  shadow-radius: 2px;
  shadow-opacity: 0.1;
  elevation: 2;
`;

function FeedCard() {
    return (
      <Root>
        <FeedCardHeader />
      </Root>
    );
}

export default FeedCard;

My main issue is that if the <Text>This is a text</Text> isn't there, the component is not rendered.我的主要问题是,如果<Text>This is a text</Text>不存在,则不会呈现组件。 When it is there, it is only the size of the contents in the component.当它在那里时,它只是组件中内容的大小。 I set the component to have a height of 50, so shouldn't it be there regardless and have the set height.我将组件设置为 50 的高度,所以它不应该在那里并且具有设置的高度。

Your Root styled component needs width as well as height and you need a colon after the height key in your CSS.您的 Root 样式组件需要宽度和高度,并且您需要在 CSS 中的高度键后加一个冒号。

const Root = styled.View`
    height: 50;
    width: 100%; // Do whatever you want it to be here.
    flex-direction: row;
    align-items: center;
    justify-content: center;
    background-color: blue;
`;

When you had text in there, it gave the element inherent width, which is why it showed up.当你在那里有文本时,它给了元素固有的宽度,这就是它出现的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM