reactjs - 当输入不聚焦时使输入标签保持不变
问题描述
我有一个带有输入和标签的样式组件。标签在聚焦时向上移动,在未聚焦时向下移动。
当输入中有值或我未聚焦输入时,如何使标签保持不变?
我的代码:
import React from "react";
import styled from "styled-components";
const Wrapper = styled.div`
position: relative;
`;
const Input = styled.input`
font-size: 18px;
padding: 10px 10px 10px 5px;
display: block;
width: 300px;
border-bottom: 1px solid #757575;
&:focus {
outline: none;
}
`;
const Label = styled.label`
color: #999;
font-size: 18px;
font-weight: normal;
position: absolute;
pointer-events: none;
left: 5px;
top: 10px;
transition: 0.2s ease all;
input:focus ~ &,
input:not(:placeholder-shown).input:not(:focus) ~ .label {
top: -20px;
font-size: 14px;
color: #5264ae;
}
`;
const FloatingInput = () => (
<Wrapper>
<Input />
<Label>First Name</Label>
</Wrapper>
);
export default FloatingInput;
解决方案
为标签添加一个required
属性input
并添加一个选择器。input:valid ~ &
当输入具有某些值时,它将变为“有效”,CSS 选择器将选择该值并应用与聚焦时相同的样式。
const Input = styled.input.attrs(() => ({
required: true,
}))`
font-size: 18px;
padding: 10px 10px 10px 5px;
display: block;
width: 300px;
border-bottom: 1px solid #757575;
&:focus {
outline: none;
}
`;
const Label = styled.label`
color: #999;
font-size: 18px;
font-weight: normal;
position: absolute;
pointer-events: none;
left: 5px;
top: 10px;
transition: 0.2s ease all;
input:focus ~ &,
input:not(:placeholder-shown).input:not(:focus) ~ .label,
input:valid ~ & {
top: -20px;
font-size: 14px;
color: #5264ae;
}
`;
const FloatingInput = () => (
<Wrapper>
<Input />
<Label>First Name</Label>
</Wrapper>
);
如果您想切换“聚焦”样式并使其在聚焦后保持不变,您将需要一些 React 状态来保持触发状态。
const Input = styled.input`
font-size: 18px;
padding: 10px 10px 10px 5px;
display: block;
width: 300px;
border-bottom: 1px solid #757575;
&:focus {
outline: none;
}
`;
const focusCSS = css`
top: -20px;
font-size: 14px;
color: #5264ae;
`;
const Label = styled.label`
color: #999;
font-size: 18px;
font-weight: normal;
position: absolute;
pointer-events: none;
left: 5px;
top: 10px;
transition: 0.2s ease all;
input:focus ~ &,
input:not(:placeholder-shown).input:not(:focus) ~ .label {
${focusCSS}
}
${({ focused }) => focused && focusCSS}
`;
const FloatingInput = () => {
const [focused, setFocused] = React.useState(false);
return (
<Wrapper>
<Input onFocus={() => setFocused(true)} />
<Label focused={focused}>First Name</Label>
</Wrapper>
);
};
推荐阅读
- javascript - 如何将外部 JS 文件导入另一个 JS 文件?
- objective-c - 使用 IOKit 的内存泄漏(改编自 USBPrivateDataSample)
- join - Power Query - 合并查询返回不正确的结果
- c++ - 如何在 constexpr C++ 代码中获得双倍 int64?
- vb.net - vb.net如何从access中获取时间数据?
- android-studio - Dart 的 SDK 在 /flutter 文件夹中的什么位置?
- android - 将多个传感器数据保存到 sqlite 数据库
- swift - 使用数组和 Firebase
- javascript - 如何获取 JavaScript 全局变量并将其发送到 php 文件中?
- groovy - Azure 架构扩展 - 错误消息:对象引用未设置为对象的实例