【关键字】
父组件 / 子组件 / 传递事件方法
【问题描述】
父组件传递事件方法(不是ui @Builder方法)给子组件,子组件可以进行调用回调数据回去,提供一下样例代码(子组件页面调用父组件方法 和 父组件页面调用子组件方法)
例如react 写法:
子组件:
export default class ChidView extends Component {
return (){
const {goCartDetail} = this.props;
<div onClick={(e)=>{goCartDetail()}}>回调</div>
}
父组件:
export default class ChidView extends Component {
goto = ()=>{
console.log('进行操作')
}
return (<div>
<ChidView goCartDetail = {()=>{this.goto()}}/>
</div>)
}
【解决方案】
父组件传递事件方法给子组件的示例代码如下:
@Component
struct Child {
@State private text: string = '初始值'
private controller: ChildController = new ChildController();
aboutToAppear() {
// 子组件调用的方法为父组件传递过来的方法
this.controller.testFunc('im the son')
// 将testFunc方法用子组件方法进行覆盖
if (this.controller) {
this.controller.testFunc = this.testFunc
}
}
// 子testFunc方法的具体实现
testFunc = (value: string) => {
this.text = value
console.log('[testFunc]testFunc call from Child')
return "[testFunc]我是儿子的方法"
}
build() {
Column() {
Text(this.text)
}
}
}
// 定义声明testFunc方法的controller
class ChildController {
// 定义子testFunc方法同名的空方法
testFunc = (value: string) => {
console.log('[testFunc]testFunc: ' + value)
return "[testFunc]我是公共定义的空方法"
}
}
@Entry
@Component
struct Parent {
private ChildRef = new ChildController()
aboutToAppear(): void {
this.ChildRef.testFunc = this.testFunc
}
// 父testFunc方法的具体实现
testFunc = (value: string) => {
console.log('[testFunc]我是父亲的testFunc方法 : ' + value)
return "[testFunc]我是父亲的方法"
}
build() {
Column() {
Text('获取Child的exposedMethods!').fontSize('18vp').fontColor(Color.Gray)
Divider()
// 将父方法作为参数传递给子组件
Child({ controller: this.ChildRef })
// 父组件调用子组件的方法
Button('Parent调用children的方法').onClick(() => {
let text = this.ChildRef.testFunc('Parent调用children的方法')
console.info('[testFunc]testFunc info:' + JSON.stringify(text))
})
}
}
}
241

被折叠的 条评论
为什么被折叠?



