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回调函数如何使用,希望本文对大家有所帮助。
原链接
- React之ref回调函数实现的两种方式
- React基础知识之Ref回调函数处理
- React * Ref回调函数处理
- react setState 的回调函数
- 回调函数的常见实现方式及速度比较
- java 回调函数实现方式
- Java 回调函数实现方式
- React之ref的使用
- C++回调函数(2)--实现回调机制的几种方式
- 什么是回调函数?回调函数的简单实现。
- 关于React的setState的回调函数
- React Native组件的生命周期及回调函数
- 两种“两数互换的方式”
- 回调函数中lpbyte的处理,ref byte与byte[]
- 回调函数实现
- react-native 之 ref 的使用
- react入坑之ref的使用
- React中setState回调函数
- Javascript 面向对象编程:封装
- linux lsof命令详解
- jsp入門
- 128. Longest Consecutive Sequence(C++)
- linux 开源镜像地址
- React之ref回调函数实现的两种方式
- 多进程多线程TCP服务器以及进程池
- 1-mvn 介绍
- vue路由配置
- matlab 两个序列的相关系数
- CSS Mastery2(9.5常见BUG&fixed/9.6分级浏览器支持/10Roma Italia实例【10.1-10.4】)
- 什么是CRC校验
- Groovy(一): build.gradle为何物?
- 数据库设计原则