Home >Web Front-end >JS Tutorial >A brief analysis of how to use ref in TypeScript and React
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.
Recommended tutorial: "JavaScript Video Tutorial"
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
Bind the scope of the subcomponent
public onRef(ref:any){ this.child = ref }Copy to clipboardErrorCopied
Bind the subcomponent Define ref
<ChildPage onRef={(el)=>this.onRef(el)} />Copy to clipboardErrorCopied
onRef and bind this (step 3, without using the arrow function)
this.onRef = this.onRef.bind(this)Copy to clipboardErrorCopied
In the subcomponent, write as follows :
1. Bind onRef in the constructor to this
this.props.onRef(this)Copy to clipboardErrorCopied
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> ) } }
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!