【问题标题】:React does not recognize the `isActive` prop on a DOM element - styled-componentsReact 无法识别 DOM 元素上的 `isActive` 属性 - 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 这个名字有什么特别之处吗?

标签: javascript css reactjs ecmascript-6 styled-components


【解决方案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);
      `};
    }
    

    【讨论】:

    【解决方案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);
      `};
    `;
    

    【讨论】:

      猜你喜欢
      • 2022-07-12
      • 2021-11-19
      • 2018-11-01
      • 2019-01-11
      • 2019-03-25
      • 2019-05-02
      • 2019-10-18
      • 2020-10-05
      • 2021-05-31
      相关资源
      最近更新 更多