[英]How to Style <Link> using styled-component
I was using this Link
from @material-ui/core/Link
in my TypeScript code and it worked perfectly:我在我的 TypeScript 代码中使用了来自
@material-ui/core/Link
这个Link
,它工作得很好:
<Link href="#" variant="body2">
Forgot?
</Link>
However, I am trying to switch to styled-components
placed in another file.但是,我正在尝试切换到放置在另一个文件中的
styled-components
。 Now, I am trying to use this (eg: https://styled-components.com/docs/basics ):现在,我正在尝试使用它(例如: https : //styled-components.com/docs/basics ):
const Link = ({ className, children}) => (
<a className={className}>
{children}
</a>
);
export const StyledLink = styled(Link)`
href: #;
variant: body2;
`;
along with:随着:
<StyledLink>Forgot?</StyledLink>
But I keep getting errors on className
and children
that Binding element 'children' implicitly has an 'any' type.ts(7031
but even if I add any
, It doesn't work.但是我不断收到关于
className
和children
错误,即Binding element 'children' implicitly has an 'any' type.ts(7031
但即使我添加了any
,它也不起作用。
What is the correct way to use styled-components in this case?在这种情况下使用样式组件的正确方法是什么? Or any other
css-in-js
alternative?或者任何其他
css-in-js
替代方案?
You should make your Link
component just like below:你应该像下面那样制作你的
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;
`;
You can use the <Link>
on top of other divs or buttons for example例如,您可以在其他 div 或按钮之上使用
<Link>
<Link><button className="Btn">Forgot?</button></Link>
you can then do two things to style the button / divs然后你可以做两件事来设置按钮/div的样式
<Link><button className="Btn" style={{backgroundColor: 'red'}}>Forgot?</button></Link>
or the second is import a separate css file或者第二个是导入一个单独的 css 文件
import classes from './ComponentName.module.css'
and then give a style然后给出一个样式
<Link><button className={classes.Btn}>Forgot?</button></Link>
This code works, and gets no warnings from the typescript compiler此代码有效,并且不会从打字稿编译器收到任何警告
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>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.