[英]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
道具的$
符号? 这将其标记为一个瞬态道具,这意味着它不会被复制到底层元素上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.