TypeScript和React如何使用ref-创新互联

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

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:申请域名、虚拟空间、营销软件、网站建设、蔚县网站维护、网站推广。

父组件

在父组件中,编写如下:

类中定义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-创新互联
网站URL:http://pwwzsj.com/article/ddgdhe.html