简体   繁体   English

如何在 React styled-components 中禁用 styled.button?

[英]How to disable a styled.button in React styled-components?

I have created the following very basic styled-components styled button:我创建了以下非常基本的 styled-components 样式按钮:

import styled from 'styled-components';

const StyledButton = styled.button``;

export const Button = () => {
    return <StyledButton>Default label</StyledButton>;
};

Then when creating an instance of one I am trying to disable it:然后在创建一个实例时,我试图禁用它:

<Button disabled />

VSCode/React is not allowing this, throwing the following error: VSCode/React 不允许这样做,抛出以下错误:

Type '{ disabled: true; }' is not assignable to type 'IntrinsicAttributes'.
    Property 'disabled' does not exist on type 'IntrinsicAttributes'.ts(2322)

HTML buttons have a disabled attribute and the styled-component docs state : HTML 按钮具有禁用属性样式组件文档 state

StyledComponent
...
This component can take any prop. It passes it on to the HTML node if it's a
valid attribute, otherwise it only passes it into interpolated functions. 
(see Tagged Template Literal)

Resulting in me being a bit stumped.导致我有点难过。 Does anyone know why this might be, please?请问有人知道为什么会这样吗?

Thank you for reading.感谢您的阅读。

you have to pass the prop to the Component and, as you are using strict react, you have to declare type of props:您必须将道具传递给组件,并且在使用严格反应时,您必须声明道具的类型:


import styled from 'styled-components';

const StyledButton = styled.button``;

export const Button = ({disabled=false}: {disabled: boolean}) => {
    return <StyledButton disabled={disabled}>Default label</StyledButton>;
};

You will need to allow props to be examined in the styled component.您将需要允许在样式组件中检查道具。 Like so像这样

import styled, { css } from "styled-components";

const buttonStyles = css`
  display: true
`;

const invertedButtonStyles = css`
  display: true
`;

const getButtonStyles = (props) => {
   
    return props.inverted ? buttonStyles : invertedButtonStyles;
  };


export const CustomButtonContainer = styled.button`
  ${getButtonStyles}
`;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM