• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 自定义组件
2<!--Kit: ArkUI-->
3<!--Subsystem: ArkUI-->
4<!--Owner: @seaside_wu1-->
5<!--Designer: @shiyu_huang-->
6<!--Tester: @TerryTsao-->
7<!--Adviser: @zhang_yixin13-->
8
9使用兼容JS的类Web开发范式的方舟开发框架支持自定义组件,用户可根据业务需求将已有的组件进行扩展,增加自定义的私有属性和事件,封装成新的组件,方便在工程中多次调用,提高页面布局代码的可读性。具体的封装方法示例如下:
10
11
12- 构建自定义组件
13  ```html
14  <!-- comp.hml -->
15   <div class="item">
16     <text class="title-style">{{title}}</text>
17     <text class="text-style" onclick="childClicked" focusable="true">点击这里查看隐藏文本</text>
18     <text class="text-style" if="{{showObj}}">hello world</text>
19   </div>
20  ```
21
22  ```css
23  /* comp.css */
24   .item {
25     width: 700px;
26     flex-direction: column;
27     height: 300px;
28     align-items: center;
29     margin-top: 100px;
30   }
31   .text-style {
32     width: 100%;
33     text-align: center;
34     font-weight: 500;
35     font-family: Courier;
36     font-size: 36px;
37   }
38   .title-style {
39     font-weight: 500;
40     font-family: Courier;
41     font-size: 50px;
42     color: #483d8b;
43   }
44  ```
45
46  ```js
47  // comp.js
48   export default {
49     props: {
50       title: {
51         default: 'title',
52       },
53       showObject: {},
54     },
55     data() {
56       return {
57         showObj: this.showObject,
58       };
59     },
60     childClicked () {
61       this.$emit('eventType1', {text: '收到子组件参数'});
62       this.showObj = !this.showObj;
63     },
64   }
65  ```
66
67- 引入自定义组件
68  ```html
69  <!-- xxx.hml -->
70   <element name='comp' src='../../common/component/comp.hml'></element>
71   <div class="container">
72     <text>父组件:{{text}}</text>
73     <comp title="自定义组件" show-object="{{isShow}}" @event-type1="textClicked"></comp>
74   </div>
75  ```
76
77  ```css
78  /* xxx.css */
79   .container {
80     background-color: #f8f8ff;
81     flex: 1;
82     flex-direction: column;
83     align-content: center;
84   }
85  ```
86
87  ```js
88  // xxx.js
89   export default {
90     data: {
91       text: '开始',
92       isShow: false,
93     },
94     textClicked (e) {
95       this.text = e.detail.text;
96     },
97   }
98  ```
99
100
101本示例中父组件通过添加自定义属性向子组件传递了名称为title的参数,子组件在props中接收。同时子组件也通过事件绑定向上传递了参数text,接收时通过e.detail获取。要绑定子组件事件,父组件事件命名必须遵循事件绑定规则,详见[自定义组件的基本用法](../reference/apis-arkui/arkui-js/js-components-custom-basic-usage.md)。自定义组件效果如下图所示:
102
103
104**图1** 自定义组件的效果
105![zh-cn_image_0000001070693737](figures/zh-cn_image_0000001070693737.png)
106
107
108## 相关实例
109
110针对自定义组件开发,有以下相关实例可供参考:
111
112- [自定义抽奖转盘(JS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/JSUI/JSCanvasComponent)
113