您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

浅析TypeScript和React中使用ref的方法

2025/12/28 16:18:41发布15次查看
typescript与react中如何使用ref?下面本篇文章给大家介绍一下ref用法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
推荐教程:《javascript视频教程》
父组件在父组件中,编写如下:
类中定义child,用于存放子组件的作用域
public child: any;copy to clipboarderrorcopied
绑定子组件作用域
public onref(ref:any){ this.child = ref}copy to clipboarderrorcopied
子组件上绑定ref
<childpage onref={(el)=>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 ( <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> ) }}
更多编程相关知识,请访问:编程视频!!
以上就是浅析typescript和react中使用ref的方法的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product