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

成都创新互联是一家专业提供镇康企业网站建设,专注与成都网站建设、成都网站制作、H5响应式网站、小程序制作等业务。10年已为镇康众多企业、政府机构等服务。创新互联专业网站制作公司优惠进行中。
父组件
在父组件中,编写如下:
类中定义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
分享地址:http://www.jxjierui.cn/article/jpopdj.html


咨询
建站咨询
