簡體   English   中英

使用 Typescript 響應樣式組件,類型錯誤

[英]React styled-component with Typescript, types error

這里有一個演示

這個應用程序正在設計一個 react 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>'

因為陣營鏈接元素需要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>;
};

或者,您可以輸入 props 對象:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM