示例效果:
提供在页面中动态添加组件,并为动态添加的组件设置属性与样式的能力(API version 8开始支持)。
属性:
createElement:
createElement(tag: string): Element 创建一个组件对象。
参数:
参数名 |
类型 |
必填 |
说明 |
tag |
string |
是 |
组件名称。 |
setAttribute:
setAttribute(name: string, value: string): void 动态设置组件属性。
参数:
参数名 |
类型 |
必填 |
说明 |
name |
string |
是 |
属性名称。 |
value |
string |
是 |
属性值。 |
setStyle:
setStyle(name: string, value: string): boolean 动态设置组件的样式。
参数:
参数名 |
类型 |
必填 |
说明 |
name |
string |
是 |
样式名称。 |
value |
string |
是 |
样式值。 |
addChild:
addChild(child: Element): void 将动态创建的组件添加到父组件当中。
参数:
参数名 |
类型 |
必填 |
说明 |
child |
Element |
是 |
组件对象。 |
示例代码:
index.hml
<div class="container">
<div id="parentDiv" class="parent"></div>
<button onclick="appendDiv" class="btn">动态创建div</button>
<button onclick="appendImage" class="btn">动态创建image组件到创建的div中</button>
</div>
index.css
.container {
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
}
.parent {
flex-direction: column;
}
.btn {
width: 70%;
margin: 15px;
padding: 20px;
}
index.js
let newDiv = null
let newImage = null
export default {
appendDiv() {
let parent = this.$element('parentDiv')
newDiv = dom.createElement('div')
newDiv.setStyle('width', '80%')
newDiv.setStyle('height', '60%')
newDiv.setStyle('backgroundColor', '#AEEEEE')
newDiv.setStyle('flexDirection', 'column')
newDiv.setStyle('alignItems', 'center')
newDiv.setStyle('justifyContent', 'center')
newDiv.setStyle('borderRadius', '20px')
parent.addChild(newDiv)
},
appendImage() {
newImage = dom.createElement('image')
newImage.setAttribute('src', 'common/test.jpeg')
// newImage.setStyle('width', '300px')
newImage.setStyle('height', '300px')
newImage.setStyle('padding', '20px')
newDiv.addChild(newImage)
}
}