HarmonyOS 鸿蒙Next中双向绑定 !!
HarmonyOS 鸿蒙Next中双向绑定 !!
@Local inputText :string = ‘’
这个不可以 双向绑定
Column(){
Text(this.inputText)
TextInput({text : this.inputText!!})
}
这个可以 双向绑定 Column(){ Text(this.inputText) TextInput({text : $$this.inputText}) }
这里!!不灵,改成 $$可以 ,组件是V2 的
[https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-new-binding](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-new-binding)
这里写的V2用!!,是我的写法不对吗
更多关于HarmonyOS 鸿蒙Next中双向绑定 !!的实战教程也可以访问 https://www.itying.com/category-93-b0.html
把build-profile的targetSdkVersion改成18试试
更多关于HarmonyOS 鸿蒙Next中双向绑定 !!的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
楼主试试把 @Local替换为 @State 或 @Link
双向绑定
@Entry
@Component
struct Example {
[@State](/user/State) inputText: string = ''; // 这里要使用[@State](/user/State)
build() {
Column() {
Text(this.inputText)
TextInput({ text: $$this.inputText }) // 使用$$
.onChange((value: string) => {
this.inputText = value; // 触发更新
})
}
}
}
或者父子组件双向同步(@Link)
// 子组件
@Component
struct ChildComponent {
[@Link](/user/Link) inputText: string; // 子组件通过[@Link](/user/Link)接收
build() {
TextInput({ text: $$this.inputText })
}
}
// 父组件
@Entry
@Component
struct ParentComponent {
[@State](/user/State) parentText: string = '';
build() {
Column() {
ChildComponent({ inputText: $parentText }) // 传递[@Link](/user/Link)
Text(this.parentText)
}
}
}
有要学HarmonyOS AI的同学吗,联系我:https://www.itying.com/goods-1206.html
v2方便一些吧,
基本信息
项目名称
示例项目
项目描述
这是一个示例项目,用于演示如何将HTML转换为Markdown。
项目状态
已完成
创建日期
2023-10-01
负责人
张三
团队成员
- 张三
- 李四
- 王五
你可以试着搭配@Event使用,但最保险的还是参考一楼的说法,要API18以上。
[@Event](/user/Event) $inputText():=>void
可以参考一下这个文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-new-binding
某些版本API不支持:
在HarmonyOS Next中,双向绑定通过@Link装饰器和组件配合实现。语法结构为[@Link](/user/Link) varName: type
,绑定数据需使用$
符号(如$varName
)。典型应用场景包括:
示例代码片段:
@Entry
@Component
struct Parent {
@State message: string = 'Hello'
build() {
Column() {
Child({ linkMessage: $message })
Text(`Parent: ${this.message}`)
}
}
}
@Component
struct Child {
[@Link](/user/Link) linkMessage: string
build() {
Button('Change')
.onClick(() => {
this.linkMessage = 'World'
})
}
}
在HarmonyOS Next中,双向绑定的语法确实需要注意版本差异。根据官方文档,V2组件使用$$
语法实现双向绑定是正确的,而!!
语法可能不适用于所有场景。
您的代码示例中:
TextInput({text: this.inputText!!})
这种写法确实可能不生效TextInput({text: $$this.inputText})
是正确的V2组件双向绑定写法
建议统一使用$$
语法进行双向绑定,这是更可靠的做法。文档中提到的!!
语法可能需要特定条件才能生效,或者在不同版本中存在兼容性差异。
对于V2组件开发,坚持使用$$
前缀可以确保双向绑定正常工作,这也是当前更推荐的写法。