首页 > 解决方案 > 输入类型密码的样式组件

问题描述

如何在 styled-components 中为 input type='password' 提供样式?

// export const Input = styled.input`
//   width: 100%;
//   height: 50px;
//   border-radius: 4px;
//   background-color: rgba(104, 105, 102, 0.1);
//   border: 1px solid #354545;
//   margin-top: 20px;
//   outline: none;
//   padding-left: 40px;
//   color: white;
//   font-size: 22px;
// `;

标签: reactjsstyled-components

解决方案


这两个例子都只是为了造型目的有点矫枉过正,可以通过使用轻松避免&[type="password"]

import styled from "styled-components";

export const Input = styled.input`
  &[type="password"] {
    border: 1px solid black;
    background: red;
  }
`;

export default function App() {
  return (
    <div>
      <div>
        <label htmlFor="username">Username</label>
        <Input id="username" type="text" />
      </div>
      <div>
        <label htmlFor="password">Password</label>
        <Input type="password" />
      </div>
    </div>
  );
}

或者,如果您想扩展基本输入组件

import styled from "styled-components";

export const Input = styled.input`
  border: 1px solid black;
`;

export const PasswordInput = styled(Input)`
  &[type="password"] {
    background: red;
  }
`;

export default function App() {
  return (
    <div>
      <div>
        <label htmlFor="username">Username</label>
        <Input id="username" type="text" />
      </div>
      <div>
        <label htmlFor="password">Password</label>
        <PasswordInput type="password" />
      </div>
    </div>
  );
}


推荐阅读