推荐教程:《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的方法的详细内容。
