【发布时间】:2021-07-25 11:40:21
【问题描述】:
我有一个下拉选择组件,它将每个选项列为一行。每行是一个 <User> 组件,由 3 个子组件组成:<Avatar>、<Username> 和 <Quota>。
我希望这 3 个组件的布局如下:
-
Avatar位于该行的最左侧,Username紧邻Avatar; -
Quota是一个可变长度的字符串;它延伸到行的右端,因此最后一个字母/数字应该刚好接触到右端。
<User
key={user.id}
isSelectValue={isSelectValue}
withBottomMargin={false}
onClick={() => {}}
>
<Avatar avatarUrl={user.avatarUrl} name={user.name} size={24} />
<Username>{user.name}</Username>
<Quota>{`${user.used}/${user.quota}`}</Quota>
</User>
对于父<User>组件和子<Username>/<Quota>组件,定义为:
export const User = styled.div`
display: flex;
align-items: center;
${mixin.clickable}
${props =>
props.isSelectValue &&
css`
margin: 0 10px ${props.withBottomMargin ? 5 : 0}px 0;
padding: 4px 8px;
border-radius: 4px;
background: ${color.backgroundLight};
transition: background 0.1s;
&:hover {
background: ${color.backgroundMedium};
}
`}
`;
export const Username = styled.div`
display: flex;
padding: 0 3px 0 8px;
${font.size(14.5)}
`;
export const Quota = styled.div`
display: flex;
padding: 0 3px 0 120px;
${font.size(14.5)}
`;
但是,目前Quota 的位置由padding: 0 3px 0 120px; 固定。如果字符串太短,它不会在行中展开/延伸到右端:
而如果字符串太长,左边会占用不够空间,向右延伸太远,会破坏整个布局:
我怎样才能使<Quota> 灵活,以便它占用足够的空间并根据其字符串长度延伸到右边框?
【问题讨论】:
-
能否请您在stackbiltz 或codesandbox 中分享您的代码?
标签: javascript css reactjs styled-components