openharmony 鸿蒙 js-components-create-elements

2025-06-12 浏览 (1)

Dynamic Component Creation

You can dynamically add components with specified attributes and styles to pages.

NOTE

This API is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.

createElement

createElement(tag: string): Element

Creates a component object.

Parameters

NameTypeMandatoryDescription
tagstringYesComponent name.

Return value

TypeDescription
ElementComponent object corresponding to the value of tag.
let newImage = dom.createElement('image')

setAttribute

setAttribute(name: string, value: string): void

Dynamically sets the attributes of this component.

Parameters

NameTypeMandatoryDescription
namestringYesAttribute name.
valuestringYesAttribute value.
newImage.setAttribute('src', 'common/testImage.jpg')

setStyle

setStyle(name: string, value: string): boolean

Dynamically sets the style of this component.

Parameters

NameTypeMandatoryDescription
namestringYesStyle name.
valuestringYesStyle value.

Return value

TypeDescription
booleanReturns true if the setting is successful; returns false otherwise.
newImage.setStyle('width', '120px')

addChild

addChild(child: Element): void

Adds a dynamically created component to the parent component.

Parameters

NameTypeMandatoryDescription
childElementYesComponent object.
newDiv.addChild(newImage)

Example

<!-- xxx.hml -->
<div class="container">
  <div id="parentDiv" class="parent"></div>
  <button onclick="appendDiv" class="btn">Dynamically create a <div> component.</button>
  <button onclick="appendImage" class="btn">Dynamically create an <image> component and add it to the newly created <div> component.</button>
</div>
/* xxx.css */
.container {
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.parent {
  flex-direction: column;
}

.btn {
  width: 70%;
  height: 60px;
  margin: 15px;
}
// xxx.js
let newDiv = null
let newImage = null

export default {
  appendDiv() {
    let parent = this.$element('parentDiv')
    newDiv = dom.createElement('div')
    newDiv.setStyle('width', '150px')
    newDiv.setStyle('height', '150px')
    newDiv.setStyle('backgroundColor', '#AEEEEE')
    newDiv.setStyle('marginTop', '15px')
    parent.addChild(newDiv)
  },
  appendImage() {
    newImage = dom.createElement('image')
    newImage.setAttribute('src', 'common/testImage.jpg')
    newImage.setStyle('width', '120px')
    newImage.setStyle('height', '120px')
    newDiv.addChild(newImage)
  }
}

你可能感兴趣的鸿蒙文章

harmony 鸿蒙JavaScript-compatible Web-like Development Paradigm (ArkUI.Full)

harmony 鸿蒙Data Type Attributes

harmony 鸿蒙button

harmony 鸿蒙chart

harmony 鸿蒙divider

harmony 鸿蒙image-animator

harmony 鸿蒙image

harmony 鸿蒙input

harmony 鸿蒙label

harmony 鸿蒙marquee

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/MPsKew