reactjs - 样式化的组件选择上一个兄弟
问题描述
我正在构建一个表单,并且在输入聚焦后尝试更改标签的颜色。我正在使用样式化组件参考 api,如果我将标记作为输入后跟标签,我会发现它可以工作,这不是我的情况。我的标记是
<FieldWrapper>
<StyledLabel htmlFor={id && id}>{label}</StyledLabel>
<StyledInput
type={type}
id={id && id}
autoComplete={autoComplete}
{...rest}
/>
</FieldWrapper>
我的样式组件文件是这样的:
const FieldWrapper = styled.div`
display: flex;
flex-wrap: wrap;
width: 100%;
position:relative;
& ${StyledInput}:focus + ${StyledLabel} {
color: red;
}
`;
有没有办法实现不必改变标记的顺序?从标记的角度来看,在标签之前输入有悖常理。
谢谢。
解决方案
首先,您需要在标签之前输入输入。您可以使用 flex-direction:row-reverse; 在输入前显示标签。然后,不要使用引用变量 ${StyledLabel},只需使用输入和标签,如下例所示:
<FieldWrapper>
<StyledInput
type={type}
id={id && id}
autoComplete={autoComplete}
{...rest}
/>
<StyledLabel htmlFor={id && id}>{label}</StyledLabel>
</FieldWrapper>
然后在样式中:
const FieldWrapper = styled.div`
display: flex;
flex-wrap: wrap;
flex-direction: row-reverse;
width: 100%;
position:relative;
input:focus ~ label{
color: green;
}
`;
推荐阅读
- javascript - 获取jquery创建的div的ID
- rabbitmq - 向新订阅者推送消息
- svelte - Svelte:App 构造函数的第二次实例化覆盖了第一次实例化,Props 进入 Stores 问题?
- python - 尝试在 Python 中格式化连接字符串 - 无法用变量替换
- java - 输入流后输出流不起作用
- amazon-web-services - 使用 MsTscLib 连接到 AWS EC2 实例
- python - 我正在尝试为项目列表执行打印语句,每个项目都在使用 \n 的新行上,但我不断收到语法错误。我找不到问题
- angular - 在 Angular 中使用日期选择器和 ASP.NET 核心 Web API 中的后端时出现服务器错误(状态:500)
- c++ - 陷入无限循环(骑士之旅问题)
- sql-server - 创建以年和月为输入的日期时间