You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建使用组件标签内容而非输入属性的Angular组件

实现带标题的插槽区块组件(统一全站边距)

你需要的是一个能接收标题属性和插槽内容的自定义组件,通过组件内部封装的样式统一标题与内容的边距,确保全站风格一致。以下是主流框架的实现方案:

Vue 3 实现

组件代码

<template>
  <div class="block-component">
    <h1 class="block-header">{{ headerText }}</h1>
    <!-- 插槽用于接收组件标签内的HTML内容 -->
    <slot></slot>
  </div>
</template>

<script setup>
// 定义组件必填的标题属性
const props = defineProps({
  headerText: {
    type: String,
    required: true
  }
});
</script>

<style scoped>
/* 组件容器统一内外边距 */
.block-component {
  padding: 16px;
  margin-bottom: 24px;
}

/* 标题固定与下方内容的间距 */
.block-header {
  margin: 0 0 12px 0;
  font-size: 20px;
}

/* 消除插槽内容默认上边距,避免额外间距 */
.block-component > *:not(.block-header) {
  margin-top: 0;
}
</style>

使用示例

<custom-component header-text="example text">
  <button>example content</button>
</custom-component>

React 实现

组件代码

import './BlockComponent.css';

export default function BlockComponent({ headerText, children }) {
  return (
    <div className="block-component">
      <h1 className="block-header">{headerText}</h1>
      {/* children对应组件标签内的所有内容 */}
      {children}
    </div>
  );
}

配套样式(BlockComponent.css)

.block-component {
  padding: 16px;
  margin-bottom: 24px;
}

.block-header {
  margin: 0 0 12px 0;
  font-size: 20px;
}

.block-component > *:not(.block-header) {
  margin-top: 0;
}

使用示例

<BlockComponent headerText="example text">
  <button>example content</button>
</BlockComponent>

核心原理

  • 借助Vue的插槽(slot)或React的children属性,自动捕获组件起始/结束标签之间的HTML内容;
  • 通过组件内部封装的CSS样式,固定容器、标题与内容的边距规则,全站所有使用该组件的区块都会自动继承统一样式,无需重复编写样式代码。

内容的提问来源于stack exchange,提问作者Erik Balgård

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 18:35:23