如何在HarmonyOS中创建一个自定义组件?

在做鸿蒙开发中,如何去创建一个自定义组件

阅读 1.1k
2 个回答

想要在鸿蒙 App 中创建一个自定义组件。

如下面示例所示:

<!-- MyCustomComponent.hml -->
<template>
  <div class="custom-component">
    <slot></slot>
  </div>
</template>

<style>
.custom-component {
  border: 1px solid black;
  padding: 10px;
}
</style>

需要创建自定义组件文件 MyCustomComponent.hmlMyCustomComponent.css

然后通过组件插槽实现自定义内容。

在主页面中使用自定义组件:

<!-- MainPage.hml -->
<template>
  <div>
    <my-custom-component>
      <text>Here is a custom component</text>
    </my-custom-component>
  </div>
</template>

<script>
import MyCustomComponent from './MyCustomComponent';

export default {
  components: {
    MyCustomComponent
  }
};
</script>

补充解释:

  • MyCustomComponent.hml:定义了一个简单的自定义组件,该组件包含一个插槽 (<slot>) 元素,用于将父组件传递的内容插入到自定义组件中。
  • MyCustomComponent.css:定义了自定义组件的样式,包括边框、填充和圆角。
  • MainPage.hml:在主页面中引入和使用自定义组件,并通过插槽将内容传递给自定义组件。

目前在 HarmonyOS 中创建自定义组件可以通过组合的方式去封装。比如要提供一个带 Text 和 Button 的组件,一般会:

@Component
struct MyComp{
  build(){
    Text()
    Button()
  }
}

ArkTs 并无“继承”的做法(未来也不会有),但提供了 Builder 和 Style 这种级别的重用。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题