Gatsby + Netlify CMS: есть ли способы включить избранные изображения для каждой записи в src / pages / index.js? - PullRequest
0 голосов
/ 13 ноября 2018

Есть ли решение для включения избранных изображений на странице TOP / HOME из шаблона https://github.com/netlify-templates/gatsby-starter-netlify-cms?

Я хотел сказать, что хочу страницу TOP / HOME (src / pages.index.js) для отображения этих изображений.

Я пытался сделать это двумя способами, но это не удалось.

Способ 1:

Из config.yml вот такниже.

  - name: "pages"
    label: "Pages"
    files:
      - file: "src/pages/index.md"
      label: "Homepage"
      name: "homepage"

Затем создайте файл разметки src / pages / index.md и переместите js-файл src / pages / index.js в каталог src / template.Добавил этот файл уценки как запись в мою коллекцию страниц.Но я получил ошибку, связанную с Гэтсби:cms написал в blog-post.js, используя компонент Content.

import React from 'react'
import PropTypes from 'prop-types'
import { Link, graphql } from 'gatsby'
import Layout from '../components/Layout'
import Content, { HTMLContent } from '../components/Content'

export default class IndexPage extends React.Component {
  render() {
    const { data } = this.props
    const { edges: posts } = data.allMarkdownRemark
    const FeaturedImg = {
      content,
      contentComponent,
    }
    const PostContent = contentComponent || Content

    return (
      <Layout>
        <FeaturedImg
          content={post.html}
          contentComponent={HTMLContent}
        />
        <section className="section">
          <div className="container">
            <div className="content">
              <h1 className="has-text-weight-bold is-size-2">Latest Stories</h1>
            </div>
            {posts
              .map(({ node: post }) => (
                <div
                  className="content"
                  style={{ border: '1px solid #eaecee', padding: '2em 4em' }}
                  key={post.id}
                >
                  <p>
                    <Link className="has-text-primary" to={post.fields.slug}>
                      {post.frontmatter.title}
                    </Link>
                    <span> &nbsp; </span>
                    <small>{post.frontmatter.date}</small>
                  </p>
                  <PostContent content={content} />
                  <p>
                    {post.excerpt}
                    <br />
                    <br />
                    <Link className="button is-small" to={post.fields.slug}>
                      Keep Reading →
                    </Link>
                  </p>
                </div>
              ))}
          </div>
        </section>
      </Layout>
    )
  }
}

IndexPage.propTypes = {
  content: PropTypes.node.isRequired,
  contentComponent: PropTypes.func,
  data: PropTypes.shape({
    allMarkdownRemark: PropTypes.shape({
      edges: PropTypes.array,
    }),
  }),
}

export const pageQuery = graphql`
  query IndexQuery {
    allMarkdownRemark(
      sort: { order: DESC, fields: [frontmatter___date] },
      filter: { frontmatter: { templateKey: { eq: "blog-post" } }}
    ) {
      edges {
        node {
          excerpt(pruneLength: 400)
          id
          fields {
            slug
          }
          frontmatter {
            title
            templateKey
            date(formatString: "MMMM DD, YYYY")
          }
        }
      }
    }
  }
`

Но, опять же, я получил такие ошибки ниже.

ERROR  Failed to compile with 1 errors                                                                                                                                                                    11:23:51

 error  in ./src/pages/index.js

Module Error (from ./node_modules/eslint-loader/index.js):

/Users/class/gatsby-netlify-blog/src/pages/index.js
  12:7   error  'content' is not defined           no-undef
  13:7   error  'contentComponent' is not defined  no-undef
  15:25  error  'contentComponent' is not defined  no-undef
  20:20  error  'post' is not defined              no-undef
  42:41  error  'content' is not defined           no-undef

✖ 5 problems (5 errors, 0 warnings)


 @ ./.cache/sync-requires.js 19:50-112
 @ ./.cache/app.js
 @ multi ./node_modules/react-hot-loader/patch.js (webpack)-hot-middleware/client.js?path=http://localhost:8000/__webpack_hmr&reload=true&overlay=false ./.cache/app

* Я уже спросил Gitter,ошибка в gatsby-starter-netlify-cms и Spectrum Chat Гэтсби, но не удалось найти правильный путь.

1 Ответ

0 голосов
/ 13 ноября 2018

Для # 1 вашему файлу уценки нужен ключ шаблона, чтобы сообщить gatsby, где найти файл js, который будет использоваться для визуализации вашей уценки.

Для # 2 эти переменные не определены в области их использования, ваш линтер ловит их, и они потерпят неудачу во время выполнения. Должны ли они быть импортированы откуда-то?

...