React styled-component with Typescript,类型错误

React styled-component with Typescript, types error

我有一个演示here

此应用正在为 React Link 组件设置样式。

我在 Link 样式组件上有一个 isActive 道具。

控制台对此抱怨,因为它无法将 isActive 识别为 a DOM 元素上的道具

文档说绕过这个的方法是

import { Link as ReactRouterDonLink } from 'react-router-dom';

然后

const Link = ({isActive, children, ...props}) => {
  return(
    <ReactRouterDonLink {...props}>
      {children}
    </ReactRouterDonLink>
  )
}

const StyledLink = styled(Link)`
  color: blue;
  font-size: 40px;
  font-family: sans-serif;
  text-decoration: none;
  font-weight: ${p => p.isActive ? 'bold': 'normal'};
`;

ReactRouterDonLink 错误地说

Property 'to' is missing in type '{ children: any; }' but required in type 'LinkProps<any>'

因为 React Link 元素需要 to

如何向 ReactRouterDonLink 添加接口以包含 to

这里的问题不是样式组件。您需要明确地将“to”属性传递给 ReactRouterDonLink 组件:

const Link = ({
  isActive,
  children,
  className,
  to
}: {
  isActive: boolean;
  children: ReactNode;
  className: string;
  to: string;
}) => {
  return <ReactRouterDonLink to={to} className={className}>{children}</ReactRouterDonLink>;
};

或者,您可以输入道具对象:

const Link = (props: {
  isActive: boolean;
  children: ReactNode;
  to: string;
  className: string;
}) => {
  return <ReactRouterDonLink to={props.to} className={props.className}>{props.children}</ReactRouterDonLink>;
};

我不明白你围绕 Link 制作的包装纸的意义所在。

您可以直接设置样式:

import React, { Component } from 'react';
import { render } from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { Link } from 'react-router-dom';
import styled from 'styled-components';
import './style.css';

// see line below for how to correctly type styled-components in TS
// using the generic type parameters that the typings expect
const StyledLink = styled(Link)<{ $isActive?: boolean }>`
  color: blue;
  font-size: 40px;
  font-family: sans-serif;
  text-decoration: none;
  font-weight: ${p => (p.$isActive ? 'bold' : 'normal')};
`;

const App = () => {
  return (
    <BrowserRouter>
      <div>
        <StyledLink to="http://www.google.com" $isActive>
          Link
        </StyledLink>
      </div>
    </BrowserRouter>
  );
};

render(<App />, document.getElementById('root'));

为什么 $ 符号代表 $isActive 道具?这将它标记为瞬态道具,这意味着它不会被复制到基础元素上。

https://styled-components.com/docs/api#transient-props