鸿蒙OS 自定义组件

2021-06-25 14:06 更新

JS UI 框架支持自定义组件,用户可根据业务需求将已有的组件进行扩展,增加自定义的私有属性和事件,封装成新的组件,方便在工程中多次调用,提高页面布局代码的可读性。具体的封装方法示例如下:

  • 构建自定义组件

  1. <!-- comp.hml -->
  2. <div class="item">
  3. <text class="title-style">{{title}}</text>
  4. <text class="text-style" onclick="childClicked" focusable="true">点击这里查看隐藏文本</text>
  5. <text class="text-style" if="{{show}}">hello world</text>
  6. </div>

  1. /* comp.css */
  2. .item {
  3. width: 700px;
  4. flex-direction: column;
  5. height: 300px;
  6. align-items: center;
  7. margin-top: 100px;
  8. }
  9. .text-style {
  10. width: 100%;
  11. text-align: center;
  12. font-weight: 500;
  13. font-family: Courier;
  14. font-size: 36px;
  15. }
  16. .title-style {
  17. font-weight: 500;
  18. font-family: Courier;
  19. font-size: 50px;
  20. color: #483d8b;
  21. }

  • 引入自定义组件

  1. <!-- xxx.hml -->
  2. <element name='comp' src='../../common/component/comp.hml'></element>
  3. <div class="container">
  4. <text>父组件:{{text}}</text>
  5. <comp title="自定义组件" show-object="{{show}}" @event-type1="textClicked"></comp>
  6. </div>

  1. /* xxx.css */
  2. .container {
  3. background-color: #f8f8ff;
  4. flex: 1;
  5. flex-direction: column;
  6. align-content: center;
  7. }

  1. // xxx.js
  2. export default {
  3. data: {
  4. text: '开始',
  5. show: false,
  6. },
  7. textClicked (e) {
  8. this.text = e.detail.text;
  9. },
  10. }

本示例中父组件通过添加自定义属性向子组件传递了名称为 title 的参数,子组件在 props 中接收,同时子组件也通过事件绑定向上传递了参数 text,接收时通过 e.detail 获取,要绑定子组件事件,父组件事件命名必须遵循事件绑定规则,详见 自定义组件开发规范。自定义组件效果如下图所示:

图1 自定义组件静态效果

点击放大

图2 自定义组件动态效果

img

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号