7.组件
<h4>组件的构造函数的几种写法</h4>
<pre><code>@Component
struct TitleBar{
@State title: string = '';
build(){
this.createText(this.title)
}
//这种写法只能被当前组件调用
@Builder createText(title: string){
Text(title);
}
}</code></pre>
<pre><code>@Component
struct TitleBar{
@State title: string = '';
build(){
createText(this.title)
}
}
//这种写法能被多个组件共同调用
@Builder function createText(title: string){
Text(title);
}</code></pre>
<h4>组件的通用事件</h4>
<pre><code>Button('按钮').width(100).height(50)
.onTouch((event: TouchEvent) =&gt; {
//触摸事件:event可以获取触摸类型(DOWN、UP、MVOE)、所有手指对应点击的坐标、目标控件宽高
})
.onClick((event: ClickEvent) =&gt; {
//点击事件:event可以获取点击位置相对屏幕的坐标,相对控件的坐标;
})
.onKeyEvent((event: KeyEvent) =&gt; {
//按键事件:仅适用于可以获取焦点的控件,event可以获取按键类型(DOWN、UP)、按键码
})</code></pre>
<h4>组件的位置设置</h4>
<ul>
<li>
<p>重叠布局</p>
<pre><code>build(){
Stack(){
Text(&quot;AAAA&quot;).fintSize(30).offset({x: 10, y: 10})//相对于自己原来的坐标位置
Text(&quot;BBBB&quot;).fontSize(15).markAnchor({x: -10, y: -10})//相对于自己原来的坐标位置
}
.align(Alignment.Center)//类似Android中FrameLayout布局的gravity属性
}</code></pre>
</li>
<li>线性布局(横向)
<pre><code>build(){
Row(){
Text(&quot;AAAA&quot;).fintSize(30)
Text(&quot;BBBB&quot;).fontSize(15).position(10, 20)//相对父控件原点的坐标位置,设置该属性后,会脱离文档流
}
.direction(Direction.Ltr)//从左至右摆放
}</code></pre></li>
</ul>
<h4>常见的控件使用</h4>
<ul>
<li>
<p>Button</p>
<pre><code>Button({type: ButtonType.Normal, stateEffect: true}){
//设置子组件,如果写了label,那么就不能写子组件了
Row(){
LoadingProgress().width(15).height(15).color(Color.White)
Text('登录中').fontSize(20)
}
}</code></pre>
</li>
<li>
<p>Checkbox</p>
<pre><code>@State isCheck = false
Checkbox({name: '不分组'})
onChange((value) =&gt; {
this.isCheck = value
})
Row(){
CheckboxGroup({group: 'sex'})
onChange((value) =&gt; {})
Text('全选')
}
Row(){
Checkbox({group: 'sex'})
Text('男')
}
Row(){
Checkbox({group: 'sex'})
Text('女')
}</code></pre>
</li>
<li>
<p>DatePicker</p>
<pre><code>DatePicker()
.lunar(true)//true 阳历;false 阴历
.onChange((value) =&gt; {})</code></pre>
</li>
<li>Navigation
<pre><code>build(){
Stack(){
Navigation()
.toolBar({item: [{value: '首页'}, {value: '我的'}]})
}
}</code></pre></li>
</ul>