温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

TypeScript和React如何使用ref

发布时间:2021-02-05 10:16:20 来源:亿速云 阅读:261 作者:小新 栏目:web开发

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

父组件

在父组件中,编写如下:

类中定义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”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI