目前,我正在尝试使用React这样渲染信息卡:
import React from 'react'
import styled from 'styled-components';
import PropTypes from 'prop-types';
const StyledInfoCard = styled.div`
display: flex;
align-items: center;
flex-wrap: wrap;
figure {
margin: 0 1.5rem 0 0;
}
`;
const InfoCard = ({ children }) => <StyledInfoCard>{children}</StyledInfoCard>;
InfoCard.propTypes = {
children: PropTypes.string.isRequired
};
/**
* @component
*/
export default InfoCard;
子级包含三个组成部分:
<InfoCard>
<Avatar alt="profile image Jonathan" source="https://images.pexels.com/photos/220453/pexels-photo-220453.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"/>
<Title size='xSmall' text="Lorem ipsum dolor sit amet, consectetur adipiscing elit" />
<subTitle size='xSmall' text="Lorem ipsum dolor sit amet, consectetur adipiscing elit" />
</InfoCard>
我的目标是渲染这样的组件:
<div>
<figure>
<img .../>
</figure>
<div>
<h2>....</h2>
<h3>.....</h3>
</div>
</div>
因此,子组件除<avatar>
组件之外还包含包装器
有什么想法吗?
答案 0 :(得分:2)
假设每个子组件Avatar
,Title
和subTitle
都是由单个节点组成的,那么不应该这样做:
<InfoCard>
<Avatar
alt="profile image Jonathan"
source="https://images.pexels.com/photos/220453/pexels-photo-220453.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"
/>
<div>
<Title size="xSmall" text="Lorem ipsum dolor sit amet, consectetur adipiscing elit" />
<subTitle size="xSmall" text="Lorem ipsum dolor sit amet, consectetur adipiscing elit" />
</div>
</InfoCard>
如果您要保留传递children
的结构,则可以修改InfoCard
:
const InfoCard = ({ children }) => {
const containedNodes = [];
const outerNodes = [];
React.Children.forEach(children, child => {
if (child.type === Avatar) {
outerNodes.push(child);
} else {
containedNodes.push(child);
}
});
return (
<StyledInfoCard>
{outerNodes}
<div>{containedNodes}</div>
</StyledInfoCard>
);
};