Using emotion/styled v11
的背景为了改变项目中所有按钮的默认type
,我为HTML<button>
编写了一个包装器组件WrappedButton
。为了允许这个新的WrappedButton
组件是styled
(styled(WrappedButton)({...})
),我需要用styled
包装我的WrapperButton
。
问题当试图设置aria-label
属性在我的WrappedButton
我得到控制台错误Using kebab-case for css properties in objects is not supported. Did you mean ariaLabel?
当我将aria-label
更改为ariaLabel
时,没有错误,但随后没有设置标签。
问题我如何在保持用例完整的情况下摆脱错误?
代码WrappedButton
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的评论中得出:
解决方案是将props
从StylableButton
的定义中删除:
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';