为什么在Sanity.IO中无法正确准备渲染

时间:2019-08-05 16:19:59

标签: sanity

我正在尝试为sanity.io中的文档自定义prview部分。为此,我创建了以下文档:

export default {
  name: 'news',
  type: 'document',
  title: 'News',
  fields: [
    {
      name: 'title',
      title: 'Title',
      type: 'string',
    },
    ...
    {
      name: 'author',
      title: 'Author',
      type: 'string',
    },
    ...
  ],
  preview: {
    select: {
      title: 'title',
      subtitle: 'author',
    }
  }
}

这完全符合我在Studio中的要求。预览窗格中的title部分显示文档的标题,而subtitle部分显示作者的姓名。

但是,如果我尝试使用author来修改prepare的输出,那么它将不再起作用。例如,看一下同一文档的以下变体:

export default {
  name: 'news',
  type: 'document',
  title: 'News',
  fields: [
    {
      name: 'title',
      title: 'Title',
      type: 'string',
    },
    ...
    {
      name: 'author',
      title: 'Author',
      type: 'string',
    },
    ...
  ],
  preview: {
    select: {
      title: 'title',
      author: 'author',
    }
  },
  prepare(selection) {
    const { author } = selection
    return {
      ...selection,
      subtitle: author && `${author} is the author`
    }
  }
}

呈现title预览字段,但subtitle部分中未显示任何内容。但是,据我了解-这应该可行。我想知道为什么不这样做。

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

prepare实际上是在预览中调用的功能。您将其作为根对象的单独字段。像这样在preview内部移动准备:

preview: {
  select: {
    title: 'title',
    author: 'author'
  },
  prepare(selection) {
    const { author } = selection
    return {
      ...selection,
      subtitle: author && `${author} is the author`
    }
  }
}
相关问题