在带有类组件的React中将引用从孩子传递给父母 [英] Passing a Ref from a Child to a Parent in React with Class Component

查看:80
本文介绍了在带有类组件的React中将引用从孩子传递给父母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在子组件中有一个iFrame,并且想要将iframe的引用传递给父组件,以便可以对iframe进行postMessage传递.我不确定如何实现从子代到父代的转发引用.

I have an iFrame in a child component, and want to pass a ref of the iframe to the parent component so I can do a postMessage to the iframe. I am unsure how to implement forwarding refs from child to parent.

谢谢!

推荐答案

如果您希望孩子参考,那很容易 ...

If you want your child reference, that's easy...

<ChildComponent
    ref={(instance) => {this.child = instance}}
/>

然后,您可以像this.child.childFunction()一样在父级中调用子级函数.

Then you can call child functions in your parent like this.child.childFunction().

如果您想获取孩子的孩子的推荐信 ,只需继续使用此模式即可.

If you want to get your child's child reference, just continue this pattern.

您的孩子班级:将您的孙子放在您的render()中.

Your child class: Set your grandchild in your render().

render() {
    return (
        <GrandChildComponent
            ref={(instance) => {this.grandchild = instance}}
        />
    );
}

您的父类:调用子组件的引用的grandchild键.

Your parent class: Call the child component's reference's grandchild key.

var grandchild = this.child.grandchild;

这篇关于在带有类组件的React中将引用从孩子传递给父母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆