ReactJS - createRef() 方法
在本文中,我们将了解如何在函数式组件中创建对任何 DOM 元素的引用。
此方法用于访问组件中的任何 DOM 元素,它返回一个可变的 ref 对象,该对象在组件置入 DOM 时一直存在。如果我们将 ref 对象传递给任何 DOM 元素,那么每当节点更改时,都会向相应的 DOM 节点元素添加 . current 属性。
语法
React.createRef()
示例
在此示例中,我们将构建一个 React 应用,它会将 ref 对象传递给两个输入字段,当点击按钮时,它会自动获取这些输入字段的数据。
App.jsx
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.fetchUsername = this.fetchUsername.bind(this);
this.fetchEmail = this.fetchEmail.bind(this);
}
fetchUsername() {
this.refs.username.value = 'RahulBansal123';
}
fetchEmail() {
this.refs.email.value = 'rahul@gmail.com';
}
render() {
return (
<div>
<input type="text" ref="username" />
<input type="text" ref="email" />
<button type="button" onClick={this.fetchUsername}>
Username
</button>
<button type="button" onClick={this.fetchEmail}>
Email
</button>
</div>
);
}
}
export default App;在上面的示例中,当点击用户名或电子邮件按钮时,将分别调用 fetchUsername 和 fetchEmail 函数,它们将 ref 对象传递给输入字段,并将其值从 null 更改为某些文本。
输出
这将生成以下结果。

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP