Jen*_*nsM 0 typescript reactjs styled-components next.js
我想知道这是否与方法styled-components,nextjs,typescript和react有任何显著的缺陷或性能问题。我想创建一个默认情况下没有样式的组件,并且可以为组件内的每个 HTML 元素提供 CSS 样式。我还需要确保提供的 CSS 样式可以与样式化的 HTML 元素将从组件接收的道具一起使用。我将展示一些代码:
可以在以下位置找到回购:Github 链接
导航.tsx
import { ReactElement, memo, useMemo, useCallback } from "react";
import Link from "next/link";
import * as S from "./navigation.styles";
import { Style } from "../../types";
export type NavigationLinks = { [key: string]: string };
type Props = {
styles?: {
navigation: Style;
link: Style;
};
links: NavigationLinks;
currentRoute: string;
};
function Navigation({
styles = { navigation: null, link: null },
links,
currentRoute,
}: Props): ReactElement {
const generateNavigationLinks = useCallback(
function(links: NavigationLinks) {
return Object.keys(links).map((linkName) => {
const href = links[linkName];
const isCurrent = href === currentRoute;
return (
<Link key={linkName} href={href}>
<S.Link styles={styles.link} active={isCurrent}>
{linkName}
</S.Link>
</Link>
);
});
},
[currentRoute, styles.link]
);
const navLinks = useMemo(() => {
return generateNavigationLinks(links);
}, [generateNavigationLinks, links]);
return <S.Navigation styles={styles.navigation}>{navLinks}</S.Navigation>;
}
export default memo(Navigation);
Run Code Online (Sandbox Code Playgroud)
导航.styles.ts
import styled from "styled-components";
import { Style, ExportProps } from "../../types";
type Props = { styles: Style };
type Activatable = { active: boolean };
export const Navigation = styled.nav<Props>`
${(props): Style => props.styles}
`;
export type LinkProps = ExportProps<Props & Activatable>;
export const Link = styled.a<Props & Activatable>`
${(props): Style => props.styles}
`;
Run Code Online (Sandbox Code Playgroud)
索引.tsx
import { ReactElement, memo } from "react";
import * as S from "../styles/index.styles";
import Navigation, {
NavigationLinks,
} from "../components/Navigation/navigation";
const navigationLinks: NavigationLinks = {
Home: "/",
Blog: "/blog",
About: "/about",
};
const navigationStyles = {
navigation: S.Navigation,
link: S.Link,
};
type Props = { currentRoute: string };
function Home({ currentRoute }: Props): ReactElement {
return (
<>
<Navigation
links={navigationLinks}
styles={navigationStyles}
currentRoute={currentRoute}
/>
</>
);
}
export default memo(Home);
Run Code Online (Sandbox Code Playgroud)
index.styles.ts
import { css } from "styled-components";
import { LinkProps } from "../components/Navigation/navigation.styles";
export const Navigation = css`
background-color: green;
`;
export const Link = css<LinkProps>`
color: ${(props): string => (props.active ? "red" : "black")};
`;
Run Code Online (Sandbox Code Playgroud)
我知道这可能是一个大问题,但我只是想知道方法是否有任何大问题或被视为“反实践”。非常感谢你的帮助!
| 归档时间: |
|
| 查看次数: |
1262 次 |
| 最近记录: |