如何使用React添加样式?

发布于 2025-02-11 14:02:34 字数 843 浏览 0 评论 0原文

在自定义的输入组件中,

import React, { InputHTMLAttributes } from "react";
import styled, { css } from "styled-components";

type InputTypeProps = {
  disabled: boolean;
};

export const MyInput: React.FC<InputHTMLAttributes<HTMLInputElement>> = (
  disabled,
  props
) => {
  return <Input type="text" disabled={disabled} {...props} />;
};

const Input = styled.input`
  ${() => css<InputTypeProps>`
    background-color: ${({ disabled }) => (disabled == false ? "white" : "gray")};
  `}
`;

当使用此组件时,

import { MyInput } from "~/components";

const Home: NextPage = () => {
  const disabled = false;
  return (
    <MyInput name="input1" disabled={disabled} />
  );
};

当我将禁用设置为true或false时,它会显示灰色。似乎这种方式不起作用。是否可以处理此HTML属性以以反应方式改变?

In a customized input component

import React, { InputHTMLAttributes } from "react";
import styled, { css } from "styled-components";

type InputTypeProps = {
  disabled: boolean;
};

export const MyInput: React.FC<InputHTMLAttributes<HTMLInputElement>> = (
  disabled,
  props
) => {
  return <Input type="text" disabled={disabled} {...props} />;
};

const Input = styled.input`
  ${() => css<InputTypeProps>`
    background-color: ${({ disabled }) => (disabled == false ? "white" : "gray")};
  `}
`;

When use this component as

import { MyInput } from "~/components";

const Home: NextPage = () => {
  const disabled = false;
  return (
    <MyInput name="input1" disabled={disabled} />
  );
};

It alwasy show gray color when I set disabled to true or false. It seems this way doesn't work. Is it possible to handle this html property to change in React way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一萌ing 2025-02-18 14:02:34

更改此。

const Input = styled.input`
background-color: white;
&:disabled {
   background-color: gray;
}
`;

Change to this.

const Input = styled.input`
background-color: white;
&:disabled {
   background-color: gray;
}
`;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文