React 无法识别 DOM 元素上的 `isActive` 属性 - styled-components

React does not recognize the `isActive` prop on a DOM element - styled-components

我在传递道具时有以下 svg 组件。

import React from 'react';
export default (props) => (
  <svg {...props}>
    <path
      d="M11.5 16.45l6.364-6.364"
      fillRule="evenodd"
    />
  </svg>
);

然后我有一个看起来像这样的 styled-component

const Icon = styled(_Icon)`
  ${props =>
    props.isActive &&
    css`
      transform: rotate(-180deg);
    `};
`;

我看到以下 react 错误。

Warning: React does not recognize the isActive prop on a DOM element.

我 运行 遇到了与样式组件相同的问题,最后我做了这样的事情:

<Icon isactive={isActive.toString()} />

${props =>
  props.isactive === 'true' &&
  css`
    transform: rotate(-180deg);
  `};
}
const StyledIcon = styled(({ isActive, ...props }) => <Icon {...props} />)`
  ${props =>
    props.isActive &&
    css`
      transform: rotate(-180deg);
    `};
`

是更简单的解决方案,它还可以防止 属性 不必要地呈现给 DOM

我有一个类似的问题并通过将道具传递到样式化组件而不是普通的 html 元素来修复错误。对于您来说,您可以将 svg 元素更改为如下内容:

import React from 'react';
export default (props) => (
  <SvgStyledComp {...props}>
    <path d="M11.5 16.45l6.364-6.364" fillRule="evenodd"/>
  </SvgStyledComp>
);
const SvgStyledComp = styled.svg`
  ${props => props.isActive && css`
    transform: rotate(-180deg);
  `};
`;

您可以使用 transient-props.

这是 tsx 示例:

Button is antd Button

import { Button } from 'antd';
import styled from 'styled-components';

interface IMyButtonProps {
    $switchShape: boolean;
    $myColor: string;
    $myBorderColor: string;
}

let MyButton = styled(Button).attrs<IMyButtonProps>((props) => {
   
    // console.log(props);
   
    let myShape = props.$switchShape ? 'circle' : 'round';

    return { type: 'primary', shape: myShape };

})<IMyButtonProps>`

    margin-left: 10px;

    ${{
        padding: '100px',
    }}

    ${(props) => {
        
        // You can get the result of Attrs
        // console.log(props);
        
        return `
            color:${props.$myColor}
        `;
    }};

    ${(props) => {
        // CSSProperties
        return {
            borderColor: props.$myBorderColor,
        };
    }};
`;

ghost is antd Button attr

<MyButton ghost={true} $switchShape $myBorderColor='black' $myColor='red'>
    click me
</MyButton>