示例效果:
提供在页面中动态添加组件,并为动态添加的组件设置属性与样式的能力(API version 8开始支持)。
示例代码:
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 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)
}
}