如何使用样式<Link>化组件设置样式



我在TypeScript代码中使用了来自@material-ui/core/LinkLink,它运行得很好:

<Link href="#" variant="body2">
Forgot?
</Link>

但是,我正在尝试切换到放置在另一个文件中的styled-components。现在,我正在尝试使用这个(例如:https://styled-components.com/docs/basics):

const Link = ({ className, children}) => (
<a className={className}>
{children}
</a>
);
export const StyledLink = styled(Link)`
href: #;
variant: body2;
`;

连同:

<StyledLink>Forgot?</StyledLink>

但我在classNamechildren上不断出现Binding element 'children' implicitly has an 'any' type.ts(7031的错误,但即使我添加了any,它也不起作用。

在这种情况下,使用样式化组件的正确方法是什么?或者任何其他css-in-js替代品?

此代码有效,并且不会从typescript编译器获得警告

import styled from "styled-components";
const Link = ({
className,
children
}: {
readonly className: string;
readonly children: React.ReactElement;
}) => (
<a href="/" className={className}>
{children}
</a>
);
export const StyledLink = styled(Link)`
href: #;
variant: body2;
color: red;
`;
function App() {
return (
<StyledLink className="classic">
<div>Forgot?</div>
</StyledLink>
);
}

您应该使Link组件如下所示:

// Link.js
import { Link } from '@material-ui/core/Link';
import styled from 'styled-components';
export default styled(Link)`
display: block;
color: #F51963;
text-decoration: none;
`;

您可以在其他div或按钮上使用<Link>,例如

<Link><button className="Btn">Forgot?</button></Link>

然后可以做两件事来设计按钮/divs 的样式

<Link><button className="Btn" style={{backgroundColor: 'red'}}>Forgot?</button></Link>

或者第二个是导入一个单独的css文件

import classes from './ComponentName.module.css'

然后给出一个样式

<Link><button className={classes.Btn}>Forgot?</button></Link>

最新更新