仅当其中有项目时才渲染组件

时间:2020-04-04 01:55:03

标签: javascript css react-native

我有一个仅当有Text时才被渲染的组件。我正在尝试为我创建的卡片div创建标题div,但是标题div不能正确呈现。

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

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;

我的主要问题是,如果<Text>This is a text</Text>不存在,则不会呈现该组件。当它在那里时,仅是组件中内容的大小。我将组件的高度设置为50,所以无论如何都不应将其放置在高度上。

1 个答案:

答案 0 :(得分:1)

您的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;
`;

当您在其中放置文字时,它会赋予元素固有的宽度,这就是为什么它出现的原因。