SuperAPI AI 工具集

canvas-component-utils

编程与开发

查看项目

更新于 10-15 15:03

技能介绍

用途

canvas-component-utils 用于在组件中正确渲染格式化文本和媒体内容。适用场景包括:从 props 渲染 HTML 文本内容、显示图片,以及处理相关内容。

项目类型判断

在应用本技能前,需检查 package.json 中是否存在名为 @drupal-canvas/headless 或以 @drupal-canvas/headless- 开头的依赖:

  • 若存在,则为 Canvas Headless 代码库,应先阅读 canvas-headless。可移植的 React 组件可在其现有公开导入路径使用 FormattedText 和 Image;FormattedText 要求 HTML 为可信或已净化。原生 Vue、Astro 和 Angular 组件应改用框架原生替代方案,而非 React 工具。
  • 若不存在,则为 Canvas 渲染的 React 代码库:组件为 React(index.jsx/.tsx),本技能内容按原样适用。

资料指出以上是仅有的两种项目类型。

导入方式

从 drupal-canvas 包导入工具:

import { FormattedText, Image } from 'drupal-canvas';

FormattedText

使用 FormattedText 从 props 渲染 HTML 内容。对于 component.yml 中任何带有 contentMediaType: text/html 的 prop,这是必需的。

示例 component.yml:

# component.yml
props:
  properties:
    text:
      title: Text
      type: string
      contentMediaType: text/html
      x-formatting-context: block
      examples:
        - <p>This is <strong>formatted</strong> text.</p>

示例用法:

import { FormattedText } from 'drupal-canvas';

const Text = ({ text, className }) => (
  <FormattedText className={className}>{text}</FormattedText>
);

何时使用 FormattedText

  • 接受富文本/HTML 内容的 props
  • 任何带有 contentMediaType: text/html 的 prop
  • 可能包含 <p>、<strong>、<em>、<a> 或其他 HTML 标签的内容

不应使用 FormattedText 的情况

  • 纯文本 props(type: string 且无 contentMediaType)
  • 标题或题目(使用常规元素)

Image

使用 Image 进行响应式图片渲染。它会自动处理响应式行为与优化。组件契约应接受单个图片对象 prop,且该 prop 匹配 $ref: json-schema-definitions://canvas.module/image;不要将该数据拆分为单独的 imageUrl/imageAlt props。

示例 component.yml:

# component.yml
props:
  properties:
    image:
      title: Image
      type: object
      $ref: json-schema-definitions://canvas.module/image
      examples:
        - src: https://example.com/photo.jpg
          alt: Description of image
          width: 800
          height: 600

示例用法:

import { Image } from 'drupal-canvas';

const Card = ({ image }) => {
  if (!image?.src) return null;

  const { src, alt, width, height } = image;
  return (
    <Image
      src={src}
      alt={alt}
      width={width}
      height={height}
      className="w-full rounded-lg object-cover"
    />
  );
};

Image props

  • src - 图片 URL(必需)
  • alt - 用于无障碍的替代文本(必需)
  • width - 原始图片宽度
  • height - 原始图片高度
  • className - 用于样式的 Tailwind 类名

适用场景

适用于 Drupal Canvas 项目中需要渲染富文本内容或响应式图片的组件开发。

限制

资料未提供本技能在具体项目之外的通用限制说明。