HarmonyOS 鸿蒙Next中关于三目中使用$$的问题

HarmonyOS 鸿蒙Next中关于三目中使用$$的问题 三目中不能直接用$$双向绑定数据吗?如:

@State oldPassword: string = ''
@State newPassword: string = ''

@Builder
item(type: number) {
    ListItem() {
      Row({ space: 20 }) {
        Text(type == 1 ? '旧密码:' : '新密码:')
          .fontSize(15)
          .fontColor('#333333')
        TextInput({ text: type == 1 ? $$this.oldPassword : $$this.newPassword })
          .fontSize(15)
          .fontColor('#666666')
      }
    }
}

更多关于HarmonyOS 鸿蒙Next中关于三目中使用$$的问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html

5 回复

要换一种写法

@State oldPassword: string = ''
@State newPassword: string = ''

@Builder

item(type: number) {
    ListItem() {
        Row({ space: 20 }) {
            Text(type == 1 ? '旧密码:' : '新密码:')
                .fontSize(15)
                .fontColor('#333333')
            if (type == 1) {
                TextInput({ text: $$this.oldPassword })
                    .fontSize(15)
                    .fontColor('#666666')
            } else {
                TextInput({ text: $$this.newPassword })
                    .fontSize(15)
                    .fontColor('#666666')
            }
        }
    }
}

更多关于HarmonyOS 鸿蒙Next中关于三目中使用$$的问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


我现在改成手动同步了, 传入数据:TextInput({ text: type == 1 ? this.oldPassword : this.newPassword }) 回传数据:.onChange((value) => { if (type == 1) { this.oldPassword = value } else if (type == 2) { this.newPassword = value } })

在HarmonyOS鸿蒙Next中,三目运算符中使用$$是ArkTS的模板字符串语法。$$用于在模板字符串中动态绑定变量或表达式,例如:

let flag = true;
let text = flag ? `Value is ${$$variable}` : `Default ${$$value}`;

$$前缀表示该变量是响应式的,当变量值变化时会触发UI更新。这种语法常用于ArkUI的声明式开发中,与状态管理结合使用。

在HarmonyOS Next中,三目运算符内直接使用$$双向绑定确实存在限制。根据您提供的代码示例,问题出在TextInput组件的text属性绑定方式上。

正确的做法应该是:

  1. 避免在三目运算符中直接使用$$绑定
  2. 改用状态变量直接绑定

修改建议:

@Builder
item(type: number) {
    ListItem() {
      Row({ space: 20 }) {
        Text(type == 1 ? '旧密码:' : '新密码:')
          .fontSize(15)
          .fontColor('#333333')
        TextInput({ 
          text: type == 1 ? this.oldPassword : this.newPassword 
        })
          .onChange((value: string) => {
            if (type == 1) {
              this.oldPassword = value;
            } else {
              this.newPassword = value;
            }
          })
          .fontSize(15)
          .fontColor('#666666')
      }
    }
}

这种实现方式既保持了双向绑定的效果,又避免了在三目运算符中使用$$语法带来的问题。

回到顶部