javascript - 组件仅在其中有项目时才呈现
问题描述
我有一个只有在有文本时才会呈现的组件。我正在尝试为我创建的卡片 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 的高度,所以它不应该在那里并且具有设置的高度。
解决方案
您的 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;
`;
当你在那里有文本时,它给了元素固有的宽度,这就是它出现的原因。