1、写出大致的计算器构造
在calcultorDemo.ets文件中
import {calculatorResult} from './calculatorResult'
import numberstack from './NumberStack'
import characterstack from './CharacterStack'
@Entry
@***ponent
struct calcultorDemo {
@State value:string =''
@State result:string=''
@State opacityValue:number=0
@State fontSizeValue:number=30
numbers :string[]=['(',')','÷','×','1','2','3','-','4','5','6','+','7','8','9']
numbers2:string[]=['%','0','.']
build() {
Column(){
calculatorResult({value:$value,result:this.result,opacityValue:$opacityValue,fontSizeValue:$fontSizeValue})
Column(){//计算机主体页面
Grid(){
GridItem(){
Text('MC')
.TextStyle()
}
.oneStyle()//MC(清零)工具
GridItem(){
Text('MR')
.TextStyle()
}
.oneStyle()
GridItem(){
Image($r('app.media.delete'))
.fillColor(Color.Blue)
.height(40)
}
.oneStyle()
.onClick(()=>{
this.value=this.value.slice(0,this.value.length-1)
this.result=''
})
GridItem(){
Text('C')
.TextStyle()
}
.oneStyle()
.onClick(()=>{
this.value=''
this.result=''
})
ForEach(this.numbers,item=>{
GridItem(){
Text(item)
.TextStyle()
}
.onClick(()=>{
if (this.value === '' && (item === '+' || item === '-' || item === '×' || item === '÷' || item === '%')) {
return
}//判断点击的第一个字符是不是运算符,若是则返回
if (this.value[this.value.length - 1] === '+' || this.value[this.value.length - 1] === '-' ||
this.value[this.value.length - 1] === '×' || this.value[this.value.length - 1] === '÷' ||
this.value[this.value.length - 1] === '%') {
// 如果当前点击的是运算符,则替换最后一个运算符
if (item === '+' || item === '-' || item === '×' || item === '÷' || item === '%') {
this.value = this.value.slice(0, this.value.length - 1) + item
} else {
this.value += item
}
} else {
this.value = this.value.concat(item)
}
})
.oneStyle()
})
GridItem(){
Text('=')
.TextStyle()
.fontColor(Color.White)
}
.rowStart(5)
.rowEnd(6)
.borderRadius(40)
.backgroundColor(Color.Blue)
.onClick(()=>{
this.result=total(checkParentheses(this.value+'#').cleanedExpression)
this.opacityValue=1
this.fontSizeValue=50
})
ForEach(this.numbers2,item=>{
GridItem(){
Text(item)
.TextStyle()
}
.onClick(()=>{this.value=this.value.concat(item)})
.oneStyle()
})
}
.width('100%')
.height(500)
.columnsTemplate('1fr 1fr 1fr 1fr')
.rowsTemplate('1fr 1fr 1fr 1fr 1fr 1fr')
.columnsGap(8)
.rowsGap(12)
.padding(12)
.backgroundColor('#fff6f0f0')
.borderRadius({topLeft:20,topRight:20})
}
.layoutWeight(1)
.justifyContent(FlexAlign.End)
}
.height('100%')
}
}
@Styles function oneStyle(){
.backgroundColor(Color.White)
.height(70)
.width(70)
.borderRadius(40)
.shadow({color:Color.Gray,radius:5})
}
@Extend(Text) function TextStyle() {
.fontSize(25)
.fontWeight(400)
}
以上代码写出计算机的键盘部分,使用Grid组件进行键盘的分隔,以及对相同功能的按钮进行ForEach循环