【问题标题】:React does not recognize the `backgroundColor` prop on a DOM elementReact 无法识别 DOM 元素上的 `backgroundColor` 属性
【发布时间】:2020-10-05 12:13:47
【问题描述】:

我一直在寻找有关此错误的信息,但找不到解决方案... 我正在使用样式化组件和 ant.design。

按钮组件

import React from 'react'
import {Btn} from './style';

const ComponentButton = (props) =>{

  const  {title, backgroundColor,color, hoverColor, handleClick,shape} = props

 return(
      <Btn 
        shape={shape || "round"} 
        onClick={handleClick}
        backgroundColor={backgroundColor}
        color={color}
        hoverColor={hoverColor}
      >
         {title}   
      </Btn>
  )
}

export default ComponentButton;

样式化组件

import styled, {css} from 'styled-components';
import {primaryColor, white} from '../../../../config';
import { Button } from 'antd';



export const Btn = styled(Button)`
   ${(props, {color, backgroundColor, hoverColor, width} = props) =>
      css`
        color: ${color ? color : white};
        background-color: ${backgroundColor ? backgroundColor : primaryColor} !important; 
        width: ${`${width}px` ? `${width}px` : '-webkit-fill-available'};
        border: none !important;

        &:hover, &:focus{
          color: ${hoverColor ? hoverColor : white};
          border: none !important;
        }
        &:after{
          box-shadow: none !important;
        }

    `} 
` 

我不知道为什么我仍然收到此错误:

React 无法识别 DOM 元素上的 backgroundColor 属性。如果您有意希望它作为自定义属性出现在 DOM 中,请将其拼写为小写 backgroundcolor

【问题讨论】:

    标签: javascript reactjs antd styled-components


    【解决方案1】:

    styled-components 默认会自动将所有的 props 添加到 DOM 元素中,例如:

      <button backgroundColor="" color="" hoverColor="" ... />
    

    react will check the props of the DOM element are legal

    另外,${(props, {color, backgroundColor, hoverColor, width} = props) 这一行看起来有点怪,应该只有一个参数。

    你可以试试这个:

    // avoid pass all props into button element
    export const Btn = styled(({color, backgroundColor, hoverColor, width, ...props}) => <Button {...props} />)`
       ${(p = props) =>
          css`
            color: ${p.color ? p.color : white};
            background-color: ${p.backgroundColor ? p.backgroundColor : primaryColor} !important; 
            width: ${`${p.width}px` ? `${p.width}px` : '-webkit-fill-available'};
            border: none !important;
    
            &:hover, &:focus{
              color: ${p.hoverColor ? p.hoverColor : white};
              border: none !important;
            }
            &:after{
              box-shadow: none !important;
            }
    
        `} 
    ` 
    

    【讨论】:

    • 你能解释一下这段代码吗?它工作正常 bt.w
    猜你喜欢
    • 2021-11-19
    • 2018-11-01
    • 2019-01-11
    • 2019-03-25
    • 2019-05-02
    • 2019-10-18
    • 2021-05-31
    • 2021-12-20
    • 2021-12-17
    相关资源
    最近更新 更多