React createRef:引用
一 代码
import React, { Component } from 'react';
class Box extends Component {
render() {
return <button>你好</button>;
}
}
export default class MyComponent extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef(); // 将引用对象设置为父组件的成员
this.boxRef = React.createRef(); // 将引用对象设置为父组件的成员
}
render() {
return <div>
{/* ref属性设置在DOM组件上,current指向html元素 */}
<input type="text" ref={this.inputRef} />
{/* ref属性设置在普通组件上,current指向普通组件 */}
<Box ref={this.boxRef}/>
</div>
}
componentDidMount() {
console.log(this.inputRef); // {current: input}
console.log(this.inputRef.current); // <input type="text">
console.log(this.inputRef.current instanceof HTMLInputElement); // true
this.inputRef.current.focus(); // 操作子组件
console.log(this.boxRef); // {current: Box}
console.log(this.boxRef.current); // Box
console.log(this.boxRef.current instanceof React.Component); // true
}
}
二 原理
React.createRef函数会创建一个引用对象(只有一个current属性)。
// react安装包中的react.development.js
// an immutable object with a single mutable(易变的) value
function createRef() {
var refObject = {
current: null
};
{
Object.seal(refObject); // 将对象密封(不能增删属性、配置属性,但可以给属性赋值)
}
return refObject;
}
子组件创建完成后,会检测其html标签中的ref属性,并做相应的处理。
html标签中的key属性、ref属性,会被React特殊处理,不会出现在props属性中!
// react-dom安装包中的react-dom.development.js
function commitAttachRef(finishedWork) {
var ref = finishedWork.ref;
if (ref !== null) {
var instance = finishedWork.stateNode;
var instanceToUse = void 0;
switch (finishedWork.tag) {
case HostComponent: // 原生html标签
// 原样返回:function getPublicInstance(instance) {return instance;}
instanceToUse = getPublicInstance(instance);
break;
default:
instanceToUse = instance; // React组件
}
if (typeof ref === 'function') { // ref是函数
ref(instanceToUse); // 执行
} else { // ref是引用对象
{
if (!ref.hasOwnProperty('current')) {
warningWithoutStack$1(
false,
'Unexpected ref object provided for %s. '
+ 'Use either a ref-setter function or React.createRef().%s',
getComponentName(finishedWork.type), getStackByFiberInDevAndProd(finishedWork));
}
}
ref.current = instanceToUse; // 设置引用对象的current属性
}
}
}
引用对象是父组件的成员,于是父组件可以通过引用对象操作子组件。
React createRef:引用的更多相关文章
- React.createRef()
概述: 引用(Refs)提供了一个获得DOM节点或者创建在render方法中的React元素的方法: 在典型的React数据流中,props是唯一的父组件与它们的子元素的通信方式.更改子元素,你需要使 ...
- React的React.createRef()/forwardRef()源码解析(三)
1.refs三种使用用法 1.字符串 1.1 dom节点上使用 获取真实的dom节点 //使用步骤: 1. <input ref="stringRef" /> 2. t ...
- react之引用echarts
react之引用echarts npm: npm install echarts --save 代码: import React, { Component } from 'react'; // 引入 ...
- React中引用CSS样式的方法
相对于html中引用css的三种方法,react中也有三种方法,一一相对: 1. 行内样式:直接在组件内部定义 <div style={{width:'20px',height:'30px'}} ...
- react.js 引用 NavBar 报错svg-spite-loader
Navbar iconName="false" 配置 改为 iconName={this.props.bool}
- React + TypeScript:元素引用的传递
React 中需要操作元素时,可通过 findDOMNode() 或通过 createRef() 创建对元素的引用来实现.前者官方不推荐,所以这里讨论后者及其与 TypeScript 结合时如何工作. ...
- React forwardRef:跳转引用
一 在DOM组件中使用 import React, { Component } from 'react'; // 跳转引用对象本身并不关心ref,而是由渲染函数转发ref const FancyBut ...
- [React] Reference a node using createRef() in React 16.3
In this lesson, we look at where we came from with refs in React. Starting with the deprecated strin ...
- react中的DOM操作
前面的话 某些情况下需要在典型数据流外强制修改子代.要修改的子代可以是 React 组件实例,也可以是 DOM 元素.这时就要用到refs来操作DOM 使用场景 下面是几个适合使用 refs 的情况 ...
随机推荐
- 【python接口自动化框架-unittest】【一】unittest单元测试框架概念
一.unittst单元测试框架 概念参考:https://docs.python.org/2/library/unittest.html 使用方法:import unittest (引入unittes ...
- PythonStudy——格式化输入小练习
# 练习:用户输入姓名.年龄.工作.爱好 ,然后打印成以下格式# ------------ info of Egon -----------# Name : Egon# Age : 22# Sex : ...
- dos2unix 批量转化文件
在windows和linux双平台下开发,同时也用git作为同步工具,但前期没有注意,导致很多文件使用windows下的换行符CRLF 参考资料了解dos2unix可以转化格式. 但有个问题,虽然可以 ...
- centos 7 su jenkins 切换不过去
root切换到jenkins用户: passwd jenkins:设置jenkins用户密码 su jenkins : 切换不过去, 查看passwd文件 cat /etc/passwd 找到:jen ...
- sql server紧急状态下登录脚本
--打开xp_cmdshell功能 EXEC [sys].[sp_configure] @configname = 'xp_cmdshell', -- varchar(35) @configv ...
- Can't parse message of type "gazebo.msgs.Packet" because it is missing required fields: stamp, type
在gazebo的仿真环境中,采用强化学习HER算法训练baxter执行reach.slide和pick and place任务. 运行HER算法,此时尚未启动gazebo仿真环境,出现如下报错: [l ...
- jQuery解决IE6/7/8不能使用 JSON.stringify 函数的问题
原文地址:http://www.ynpxrz.com/n1445665c2023.aspx JSON 对象是在 ECMAScript 第 5 版中实现的,此版于 2009 年 12 月发布:IE6 I ...
- python:数据类型list
一.列表list list是python中基础的数据类型之一,它是以[ ]括起来,每个元素以逗号隔开,而且他里面可以存放各种数据类型 li = ['alex', 123, True, (1, 2, 3 ...
- Linux报错:bash: pip: command not found
$ wget https://bootstrap.pypa.io/get-pip.py$ python get-pip.py$ pip -V #查看pip版本 接下来就可以随便pip安装东西了
- Includes() vs indexOf() in JavaScript
碰到一个问题, 部分机器网页数据源不正常, 简单排查发现是使用了较新的Array.includs 方法. 查了下兼容性, chrome 需要47版本以后支持, 客户机果然是很久的43版本. 用Arra ...