大家都知道,父@State与子@Link,这样搭配是可以实现父数据变化,子组件的相应变量也会更新,子组件的变量变化了,父组件的也相应的变量,俗称“双向绑定”(Two-way binding),但我发现一个问题,拥有此功能的还有一个$$,这就让我产生了疑问,它们两们有什么区别?
我的理解就是当父组件和子组件都是咱们自己写的,那么使用父@State与子@Link,当父组件是我们写的,而子组件不是,已经被系统或者第三方封装好了后,这时就要按要求来,使用$$,而这些子组件的某些字段是支持$$的,有定数的,在鸿蒙开发当中,如下系统列表支持$$:
| 组件 | 支持的参数/属性 | 起始API版本 |
|---|---|---|
| Checkbox | select | 10 |
| CheckboxGroup | selectAll | 10 |
| DatePicker | selected | 10 |
| TimePicker | selected | 10 |
| MenuItem | selected | 10 |
| Panel | mode | 10 |
| Radio | checked | 10 |
| Rating | rating | 10 |
| Search | value | 10 |
| SideBarContainer | showSideBar | 10 |
| Slider | value | 10 |
| Stepper | index | 10 |
| Swiper | index | 10 |
| Tabs | index | 10 |
| TextArea | text | 10 |
| TextInput | text | 10 |
| TextPicker | selected、value | 10 |
| Toggle | isOn | 10 |
| AlphabetIndexer | selected | 10 |
| Select | selected、value | 10 |
| BindSheet | isShow | 10 |
| BindContentCover | isShow | 10 |
| Refresh | refreshing | 8 |
| GridItem | selected | 10 |
| ListItem | selected | 10 |
例子:
@Component
struct ChildComponent{@Prop cusername:stringbuild() {Column(){Text(`子组件用户名:${this.cusername}`)TextInput({text:$$this.cusername})}.backgroundColor(Color.Pink)}
}
当TextInput使用$$时,使用输入法改变TextInput的值,cusername也会改变,cusername变时,也会同步给TextInput,实现了双向绑定。
总结:
自己写的使用父@State与子@Link,更灵活,我随业务随意增减,无任务限制
当使用现成的组件时,为了实现双向绑定,得按照特定字段来使用$$来,使用方便,但限制比较多,范围小!
