高仿网易云的笔记记录-day4
对网页进行设计
在components中创建app-header和app-footer文件夹和index.tsx
在他们之中写网页逻辑
使用styled-components来对页面写样式
现在终端安装:
npm install styled-component -D在对应组件的文件夹中创建style.ts(如在app-header下创建)
在整个项目下面创建声明文件style.d.ts
// src/styled.d.ts import 'styled-components' declare module 'styled-components' { export interface DefaultTheme { color: { primary: string secondary: string } size: Record<string, unknown> // ✅ 修复:使用 Record mixin: Record<string, never> } }因为是ts文件所以需要针对该依赖安装类型声明
npm install @types/styled-components -Dexport const HeaderWrapper = styled.div``这行代码做了三件重要的事情:
1. 创建样式化组件
styled.div表示你要创建一个<div>元素的样式化版本它返回一个React 组件,这个组件会自动应用你定义的 CSS 样式
2. 定义组件名称
HeaderWrapper是你给这个样式化组件起的名字这个名字应该描述性地表达这个组件的用途
3. 导出组件
export关键字表示这个组件可以被其他文件导入使用
将heaferWrapper导出到index.tsx里面就可以使用了,在style.ts中继续编写组件
(注意!export const HeaderWrapper = styled.div``由两个点括起来)
在哪里编辑总体主题?
在assets中创建theme文件夹和index,在其中编辑theme主题
// theme.js const theme = { color: { primary: '#C20C0C', secondary: '' }, size: {}, mixin: { wrapv1: ` width: 1100px; margin: 0 auto; ` } } export default theme混入:mixin
格式为;
mixin: { // 页面内容区域居中 wrapv1: ` width: 1100px; margin: 0 auto; `, // 文字超出显示省略号 textEllipsis: ` white-space: nowrap; overflow: hidden; text-overflow: ellipsis; `, // 水平居中 flexCenter: ` display: flex; justify-content: center; align-items: center; `使用改固定样式来编写高复用率的样式款式 `
mixin: { wrapv1: ` width: 1100px; margin: 0 auto; `, flexCenter: ` display: flex; justify-content: center; align-items: center; ` }在src下创建文件夹src/styled.d.ts文件
// src/styled.d.ts import 'styled-components'; declare module 'styled-components' { export interface DefaultTheme { color: { primary: string; secondary: string; }; size: Record<string, unknown>; // 或者更具体的类型 mixin: { wrapv1: string; }; } }然后去到整个文件的目录的index.ts,导入ThemeProvider,编辑好对应的属性
用ThemeProvider包裹好:
<ThemeProvider theme={theme}> <HashRouter> <App /> </HashRouter> </ThemeProvider>使用ThemeProvider包裹好后,theme中设置的混入就可以让全部人使用了
但是!我们不用定义混用而是使用直接定义类,然后给对应组件添加类名
后续导入先行项目材料(精灵图、css)
对顶部header继续设计
对header部分数据进行填写,在data创建header-titles.json
将数据统一到json数据中管理
[ { "title": "发现音乐", "type": "path", "link": "/discover" }, { "title": "我的音乐", "type": "path", "link": "/mine" }, { "title": "关注", "type": "path", "link": "/focus" }, { "title": "商城", "type": "link", "link": "https://music.163.com/store/product" }, { "title": "音乐人", "type": "link", "link": "https://music.163.com/st/musician" }, { "title": "下载客户端", "type": "path", "link": "/download" } ]然后在index中调用:
import headerTitles from '@/assets/data/header_title.json'<div className="title-list"> {headerTitles.map((item) => { return ( <div className="item" key={item.title}> {showItem(item)} </div> ) })} </div>编辑showItem中的if等逻辑
function showItem(item: any) { if (item.type === 'path') { return <Link to={item.path}>{item.title}</Link> } else { return ( <a href={item.link} target="_blank" rel="noopener noreferrer"> {item.title} </a> ) } }