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

Posted

技术标签:

【中文标题】React 无法识别 DOM 元素上的 `isActive` 属性 - styled-components【英文标题】:React does not recognize the `isActive` prop on a DOM element - styled-components 【发布时间】:2020-02-15 05:58:46 【问题描述】:

我有以下 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 错误。

警告:React 无法识别 DOM 元素上的 isActive 属性。

【问题讨论】:

isActive 这个名字有什么特别之处吗? 【参考方案1】:
const StyledIcon = styled(( isActive, ...props ) => <Icon ...props />)`
  $props =>
    props.isActive &&
    css`
      transform: rotate(-180deg);
    `;
`

是一种更简单的解决方案,它还可以防止属性被不必要地渲染到 DOM

【讨论】:

【参考方案2】:

我在 styled-components 上遇到了同样的问题,我最终做了这样的事情:

<Icon isactive=isActive.toString() />

$props =>
  props.isactive === 'true' &&
  css`
    transform: rotate(-180deg);
  `;

【讨论】:

谢谢!这有点hacky,还是您认为这是最好的方法?这里没有任何明确的解决方案 - github.com/styled-components/styled-components/pull/2093 这有点hacky,没有关于如何做的适当文档......【参考方案3】:

我遇到了类似的问题,并通过将道具传递给样式化组件而不是普通的 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);
  `;
`;

【讨论】:

以上是关于React 无法识别 DOM 元素上的 `isActive` 属性 - styled-components的主要内容,如果未能解决你的问题,请参考以下文章

React 无法识别 DOM 元素上的 `toggleNode` 属性

React 包装器:React 无法识别 DOM 元素上的 `staticContext` 道具

React 包装器:React 无法识别 DOM 元素上的 `staticContext` 道具

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

Styled-components:React 无法识别 DOM 元素上的 `lineHeight` 道具

在 DOM 中添加新元素后,该元素无法识别旧脚本