HarmonyOS 鸿蒙Next记录当引入自定义组件有TextInput时,获取子组件输入框的值方法【1】使用@Link【2】使用onChange回调

发布于 1周前 作者 gougou168 来自 鸿蒙OS

HarmonyOS 鸿蒙Next记录当引入自定义组件有TextInput时,获取子组件输入框的值方法【1】使用@Link【2】使用onChange回调

【方案一】使用@Link

cke_205.png

@Component
struct LoginEditCompoments {
@Link inputValue :string

build() { TextInput({text:$$this.inputValue}) } }

@Entry @Component struct Page04 { @State inputValue_1: string = “” @State inputValue_2: string = “”

build() { Column({ space: 10 }) { LoginEditCompoments({ inputValue:this.inputValue_1 }) LoginEditCompoments({ inputValue:this.inputValue_2 }) Button(‘登录’).onClick(() => { console.info(inputValue_1:${<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.inputValue_1}) console.info(inputValue_2:${<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.inputValue_2}) }) } .height(‘100%’) .width(‘100%’) } }<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

打印

inputValue_1:555
inputValue_2:7<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

【2】使用onChange回调

cke_12408.png

@Component
struct LoginEditCompoments {
onTextChange?: (value: string) => void

build() { TextInput().onChange((value: string) => { if(this.onTextChange){ this.onTextChange(value) } }) } }

@Entry @Component struct Page04 { @State inputValue_1: string = “” @State inputValue_2: string = “”

build() { Column({ space: 10 }) { LoginEditCompoments({ onTextChange: (value) => { this.inputValue_1 = value } }) LoginEditCompoments({ onTextChange: (value) => { this.inputValue_2 = value } }) Button(‘登录’).onClick(() => { console.info(inputValue_1:${<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.inputValue_1}) console.info(inputValue_2:${<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.inputValue_2}) }) } .height(‘100%’) .width(‘100%’) } }<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

打印

inputValue_1:777
inputValue_2:5<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>


关于HarmonyOS 鸿蒙Next记录当引入自定义组件有TextInput时,获取子组件输入框的值方法【1】使用@Link【2】使用onChange回调的问题,您也可以访问:https://www.itying.com/category-93-b0.html 联系官网客服。

回到顶部