迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 >

React之ref回调函数实现的两种方式

作者:迹忆 最近更新:2022/12/04 浏览次数:

《React组件refs详解》这篇文章中,我们讲解了ref的使用场景和使用方法。其中举了一个例子:通过某个事件使input元素获得焦点。

这里我们还借用这个例子,在原先的例子中我们使用的是ref字符串的方式,在本篇我们将要是用回调函数的方式来实现。

ES6回调函数

这里我们使用ES6回调函数实现获取焦点

var MyComponent = React.createClass({
    handleClick: function() {
        // Explicitly focus the text input using the raw DOM API.
        if (this.myTextInput !== null) {
            this.myTextInput.focus();
        }
    },
    render: function() {
      return (
            <div>
                <input type="text" ref={ (ref)=>this.myTextInput = ref } />
                <input
                    type="button"
                    value="Focus the text input"
                    onClick={this.handleClick}
                    />
            </div>
        );
    }
});

CommonJs回调函数实现

var MyComponent = React.createClass({
    handleClick: function() {
        // Explicitly focus the text input using the raw DOM API.
        if (this.myTextInput !== null) {
            this.myTextInput.focus();
        }
    },
    render: function() {
      return (
            <div>
                <input type="text" ref={ function(ref){this.myTextInput = ref}.bind(this) } />
                <input
                    type="button"
                    value="Focus the text input"
                    onClick={this.handleClick}
                    />
            </div>
        );
    }
});

注意:在上面代码中,使用的是CommonJs语法,回调函数function(){}后面有.bind(this)。这是需要注意的地方,绑定this,使function内的this对象是该组件。如果不绑定this,那么在handleClick中的this.myTextInput将会报未定义的错误。这是需要注意的地方,在ES6中就不存在这个问题。

本文的目的就是通过实例来介绍ref回调函数如何使用,希望本文对大家有所帮助。

相关文章

在 React 中添加事件监听器

发布时间:2023/03/08 浏览次数:179 分类:WEB前端

事件侦听器对于单页应用程序至关重要。在本文中,我们将探讨如何在 React 中添加它们。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便