【问题标题】:Component only rendered if there is an item in it组件仅在其中有项目时才呈现
【发布时间】:2020-04-04 01:55:03
【问题描述】:

我有一个只有在有文本时才会呈现的组件。我正在尝试为我创建的卡片 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;

我的主要问题是,如果 &lt;Text&gt;This is a text&lt;/Text&gt; 不存在,则不会呈现组件。当它在那里时,它只是组件中内容的大小。我将组件的高度设置为 50,所以它不应该在那里并且具有设置的高度。

【问题讨论】:

    标签: javascript css react-native


    【解决方案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;
    `;
    

    当你有文本时,它给了元素固有的宽度,这就是它出现的原因。

    【讨论】:

      猜你喜欢
      • 2016-01-08
      • 2016-10-03
      • 2021-12-31
      • 1970-01-01
      • 2021-04-01
      • 2019-05-14
      • 2020-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多