簡體   English   中英

React 樣式:Wrapper 組件生成`不支持將 kebab-case 用於對象中的 css 屬性。 您是說 ariaLabel?` 錯誤

[英]React styled: Wrapper component produces `Using kebab-case for css properties in objects is not supported. Did you mean ariaLabel?` error

使用情感/風格 v11

背景

為了更改項目中所有按鈕的默認type ,我為 HTML <button>編寫了一個包裝器組件WrappedButton 為了讓這個新的WrappedButton組件具有styledstyled(WrappedButton)({...}) ),我需要用styled包裝我的WrapperButton

問題

嘗試在我的WrappedButton上設置aria-label屬性時,出現控制台錯誤Using kebab-case for css properties in objects is not supported. Did you mean ariaLabel? Using kebab-case for css properties in objects is not supported. Did you mean ariaLabel?

當我將aria-label更改為ariaLabel時,沒有錯誤,但隨后未設置 label。

問題

如何在保持用例完好無損的同時消除錯誤?

代碼

包裹按鈕


type ButtonPropsType = React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>;
type RefType = ((instance: HTMLButtonElement | null) => void) | React.RefObject<HTMLButtonElement> | null | undefined;

/** 
  * This is needed in order to allow the button to be styled by
  * emotion (`styled(WrappedButton)({...})`
 **/
const StylableButton = styled.button({}, (props: ButtonPropsType) => ({
    ...(props as any),
}));

// change default `type` from `submit` to `button`
const defaultProps: ButtonPropsType = {
    type: 'button',
};

export const WrappedButton = forwardRef((props: ButtonPropsType, ref: RefType) => {
    return <StylableButton {...defaultProps} ref={ref} {...props} />;
});
WrappedButton.displayName = 'Button';

用法

test('A', () => {
    render(<WrappedButton aria-label='foo'>a</WrappedButton>);
});

我試過的:

shouldForwardProp

const StylableButton = styled('button',
  {
  //shouldForwardProp: (prop) => (prop !== 'aria-label')
  }
)({}, (props: ButtonPropsType) => ({
    shouldForwardProp: (prop) => (prop !== 'aria-label'),
    ...(props as any),
}));

vighnesh153的評論中得出:

解決方案是從StylableButton的定義中刪除對props的提及:

const StylableButton = styled.button();

顯然,一切都在幕后按預期進行,更不用說道具了。

這是完整的來源:

type ButtonPropsType = React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>;
type RefType = ((instance: HTMLButtonElement | null) => void) | React.RefObject<HTMLButtonElement> | null | undefined;

/** 
  * This is needed in order to allow the button to be styled by
  * emotion (`styled(WrappedButton)({...})`
 **/
const StylableButton = styled.button();

// change default `type` from `submit` to `button`
const defaultProps: ButtonPropsType = {
    type: 'button',
};

export const WrappedButton = forwardRef((props: ButtonPropsType, ref: RefType) => {
    return <StylableButton {...defaultProps} ref={ref} {...props} />;
});
WrappedButton.displayName = 'Button';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM