1. 全局用法
目录结构:(我不会画目录树,用markdown吧)
- pages
- _app.js
- index.tsx
- style.css
- .next
- node_modules
- tsconfig.json
步骤
- 在pages文件夹下创建_app.js文件
示例代码如下
import '../style.css';
export default function Container({
Component,
pageProps
}) {
return <Component {
...pageProps
}
/>
}
可以看到,这里导出了一个工厂函数Container,该函数利用接收的Component和pageProps生成一个船新组件,并导出。 ps其实就是react函数式组件的写法
- 在pages文件夹下创建index.tsx
页面内引用Container,并把你的组件和props传递给Container,
示例代码如下
import Container from './_app';
const Index: React.FC = (props) => {
return (
<Container Component={Page} pageProps={{}}></MyApp>
)
}
const Page = () => {
console.log('Page reander..');
return (
<div>hello world</div>
)
}
export default Index;
npx next dev 看看效果
本质就是jsx的套娃,理解不难。
2.css modules 用法
这种用法针对粒度小的组件
1. 目录结构
- components
- Board.tsx
- Board.module.css
- pages
- index.tsx
- .next
- node_modules
- tsconfig.json
- 在根目录下创建文件夹components,其内创建文件
Board.tsx、Board.module.css
示例代码如下
.title {
color: red;
}
import style from './Board.module.css';
const Board: React.FC = (props) => {
return (
<div className={style.title}>component Board title</div>
)
}
export default Board;
- 在pages下index.tsx内写
import Board from '../components/board';
const Index: React.FC = (props) => {
return (
<Board />
)
}
export default Index;
npx next dev 看看效果