React style: Wrapper组件不支持在对象中的css属性中使用kebab-case.你说的是一个标签吗?的



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的评论中得出:

解决方案是将propsStylableButton的定义中删除:

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';

最新更新