React之ref的使用

来源:互联网 发布:贵金属喊单软件 编辑:程序博客网 时间:2024/06/06 19:39
在本篇我们将要是用回调函数的方式来实现。

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

原创粉丝点击