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

来源:互联网 发布:远程火箭炮知乎 编辑:程序博客网 时间:2024/05/17 13:14

在《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回调函数如何使用,希望本文对大家有所帮助。

原链接