React does not recognize the `` prop on a DOM element.

3,894 阅读1分钟

React does not recognize the `` prop on a DOM element.

在使用 React 和 styled-components时,可能会遇到这样的写法

interface ButtonProps {
  children: React.ReactNode
  borderRadius?: string
  //...
}

export const Button: React.FC<ButtonProps> = ({ children, ...rest }: ButtonProps) => {
  return <ButtonWrapper {...rest}>{children}</ButtonWrapper>
}

const ButtonWrapper = styled.button<{ borderRadius?: string }>`
  border-radius: ${({ borderRadius }) => borderRadius && borderRadius};
`

此时,控制台就会出现一个报错:React does not recognize the `borderRadius` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `disabledbackgroundcolor` instead. If you accidentally passed it from a parent component, remove it from the DOM element.

解决方法

在查阅官方文档后,找到了解决方法,在borderRadius 这类元素前面加一个 $

export const Button: React.FC<ButtonProps> = ({ borderRadius, children, ...rest }: ButtonProps) => {
  return <ButtonWrapper $borderRadius={borderRadius} {...rest}>{children}</ButtonWrapper>
}

const ButtonWrapper = styled.button<{ $borderRadius?: string }>`
  border-radius: ${({ $borderRadius }) => $borderRadius && $borderRadius};
`

官方文档:styled-components.com/docs/api#tr…