【问题标题】:How to disable a styled.button in React styled-components?如何在 React styled-components 中禁用 styled.button?
【发布时间】:2021-08-04 04:22:00
【问题描述】:

我创建了以下非常基本的 styled-components 样式按钮:

import styled from 'styled-components';

const StyledButton = styled.button``;

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

然后在创建一个实例时,我试图禁用它:

<Button disabled />

VSCode/React 不允许这样做,抛出以下错误:

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

HTML 按钮 have a disabled attributestyled-component docs 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)

导致我有点难过。请问有谁知道为什么会这样?

感谢您的阅读。

【问题讨论】:

  • 你没有为你的按钮声明任何属性
  • 将所有的 props 散布到按钮组件上

标签: javascript reactjs typescript styled-components


【解决方案1】:

您必须将道具传递给组件,并且由于您使用严格的反应,您必须声明道具的类型:


import styled from 'styled-components';

const StyledButton = styled.button``;

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

【讨论】:

    【解决方案2】:

    您需要允许在样式化组件中检查道具。像这样

    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}
    `;
    

    【讨论】:

      猜你喜欢
      • 2017-11-18
      • 2022-01-26
      • 2021-01-09
      • 2021-04-13
      • 2018-04-14
      • 2021-07-13
      • 2017-07-20
      • 2019-02-18
      • 1970-01-01
      相关资源
      最近更新 更多