Home > Web Front-end > JS Tutorial > A brief analysis of how to use ref in TypeScript and React

A brief analysis of how to use ref in TypeScript and React

青灯夜游
Release: 2021-02-05 10:01:14
forward
3288 people have browsed it

How to use ref in TypeScript and React? The following article will introduce you to the usage of ref. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

A brief analysis of how to use ref in TypeScript and React

Recommended tutorial: "JavaScript Video Tutorial"

Parent component

In the parent component , written as follows:

Child is defined in the class to store the scope of the subcomponent

public child: any;Copy to clipboardErrorCopied
Copy after login

Bind the scope of the subcomponent

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

Bind the subcomponent Define ref

<ChildPage onRef={(el)=>this.onRef(el)} />Copy to clipboardErrorCopied
Copy after login

onRef and bind this (step 3, without using the arrow function)

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

Subcomponent

In the subcomponent, write as follows :

1. Bind onRef in the constructor to this

this.props.onRef(this)Copy to clipboardErrorCopied
Copy after login

After completing the above 4 steps, the parent component can call the state value and method in the child component at will.

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 (
           <div>
               <span>父组件</span>
               <ChildCom onRef={this.onRef}></ChildCom>
           </div>
        )
    }
}
interface childProps{
    onRef? : any
}
export class ChildCom extends React.Component<childProps, {}> {
    constructor(props:{}){
        super(props);
        this.props.onRef(this);
    }


    testFun(){
        console.log(123)
    }

    render(){
        return (
           <div>
               <span>子组件</span>
           </div>
        )
    }
}
Copy after login

For more programming-related knowledge, please visit: Programming Video! !

The above is the detailed content of A brief analysis of how to use ref in TypeScript and React. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template