资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

TypeScript和React如何使用ref

这篇文章给大家分享的是有关TypeScript和React如何使用ref的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

成都创新互联是一家专业提供镇康企业网站建设,专注与成都网站建设、成都网站制作H5响应式网站、小程序制作等业务。10年已为镇康众多企业、政府机构等服务。创新互联专业网站制作公司优惠进行中。

父组件

在父组件中,编写如下:

类中定义child,用于存放子组件的作用域

public child: any;Copy to clipboardErrorCopied

绑定子组件作用域

public onRef(ref:any){
 this.child = ref
}Copy to clipboardErrorCopied

子组件上绑定ref

this.onRef(el)} />Copy to clipboardErrorCopied

onRef 绑定this(第3步,不使用箭头函数的情况)

this.onRef = this.onRef.bind(this)Copy to clipboardErrorCopied

子组件

在子组件中,编写如下:

1、constructor中onRef绑定this

this.props.onRef(this)Copy to clipboardErrorCopied

完成以上4步骤,父组件中可以随便调用子组件中state的值以及方法。

export class ParentCom extends React.Component<{}, {}> {
    constructor(props:{}){
        super(props);
        this.onRef = this.onRef.bind(this);
    }
    public child: any;

    onRef(ref:any){
        this.child = ref;
    }

    getChildFun(){
        this.child.testFun();
    }

    render(){
        return (
           
               父组件                            
        )     } } interface childProps{     onRef? : any } export class ChildCom extends React.Component {     constructor(props:{}){         super(props);         this.props.onRef(this);     }     testFun(){         console.log(123)     }     render(){         return (            
               子组件            
        )     } }

感谢各位的阅读!关于“TypeScript和React如何使用ref”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!


本文标题:TypeScript和React如何使用ref
浏览地址:http://cdkjz.cn/article/jpopdj.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220