造型我们的主页

现在我们在主页面添加一些样式。 (pages/index.js)

只需用以下代码替换pages/index.js

  1. import Layout from '../components/MyLayout.js'
  2. import Link from 'next/link'
  3. function getPosts () {
  4. return [
  5. { id: 'hello-nextjs', title: 'Hello Next.js'},
  6. { id: 'learn-nextjs', title: 'Learn Next.js is awesome'},
  7. { id: 'deploy-nextjs', title: 'Deploy apps with ZEIT'},
  8. ]
  9. }
  10. export default () => (
  11. <Layout>
  12. <h1>My Blog</h1>
  13. <ul>
  14. {getPosts().map((post) => (
  15. <li key={post.id}>
  16. <Link as={`/p/${post.id}`} href={`/post?title=${post.title}`}>
  17. <a>{post.title}</a>
  18. </Link>
  19. </li>
  20. ))}
  21. </ul>
  22. <style jsx>{`
  23. h1, a {
  24. font-family: "Arial";
  25. }
  26. ul {
  27. padding: 0;
  28. }
  29. li {
  30. list-style: none;
  31. margin: 5px 0;
  32. }
  33. a {
  34. text-decoration: none;
  35. color: blue;
  36. }
  37. a:hover {
  38. opacity: 0.6;
  39. }
  40. `}</style>
  41. </Layout>
  42. )

看看<style jsx>元素。 这是我们编写我们的CSS规则的地方。

替换此代码后,我们的博客的主页将如下所示:

造型我们的主页 - 图1

在上面的代码中,我们没有直接在样式标签中编写样式; 而是写在模板字符串中。

现在尝试直接编写CSS而不使用模板字符串({` `})。 像这样:

  1. <style jsx>
  2. h1, a {
  3. font-family: "Arial";
  4. }
  5. ul {
  6. padding: 0;
  7. }
  8. li {
  9. list-style: none;
  10. margin: 5px 0;
  11. }
  12. a {
  13. text-decoration: none;
  14. color: blue;
  15. }
  16. a:hover {
  17. opacity: 0.6;
  18. }
  19. </style>

会发生什么?

  1. ✦没有变化
  2. ✦新风格不见了
  3. ✓在页面上显示错误:“SyntaxErrorUnexpected token
  4. ✦在页面上显示错误:“提供的样式无效”