react的refs属性

refs

Refs 提供了一种方式,允许我们访问 DOM 节点或在 render 方法中创建的 React 元素

创建refs

字符串形式refs(过时了)
// ref key为自命名内容, value为节点 input
class Demo extends React.Component {
showData = () => {
// 拿到的是真实DOM
const { input1 } = this.refs;
alert(input1.value);
}
showData2 = () => {
const { input2 } = this.refs;
alert(input2.value);
}
render() {
return (
<div>
<input ref="input1" type="text" placeholder="点击按钮提示数据" /> &nbsp;
<button onClick={this.showData}>点我提示</button>&nbsp;
<input onBlur={this.showData2} ref="input2" type="text" placeholder="失去焦点提示" />
</div>
)
}
}
回调函数形式refs
// 回调函数中c是当前节点,this.input1的Demo实例的属性
class Demo extends React.Component {
showData = () => {
// 拿到的是真实DOM
const { input1 } = this;
alert(input1.value);
}
showData2 = () => {
const { input2 } = this;
alert(input2.value);
}
// 直接调用
showInfo = (c) => {
this.input2 = c;
}
render() {
return (
<div>
<input ref={c => this.input1 = c} type="text" placeholder="点击按钮提示数据" /> &nbsp;
<button onClick={this.showData}>点我提示</button>&nbsp;
<input ref={this.showInfo} onBlur={this.showData2} type="text" placeholder="失去焦点提示" />
</div>
)
}
}
createRef(react16.3后)
class Demo extends React.Component {
// React.createRef 调用后可以返回一个容器,该容器可以存储被ref所表示的节点
// 即创建一个容器,将input节点放入容器中
// 一个容器存一个节点
myRef = React.createRef();
showData = () => {
// 拿到的是真实DOM
const value = this.myRef.current.value;
alert(value);
}
render() {
return (
<div>
<input ref={this.myRef} type="text" placeholder="点击按钮提示数据" /> &nbsp;
<button onClick={this.showData}>点我提示</button>&nbsp;
</div>
)
}
}

访问refs

当 ref 被传递给 render 中的元素时,对该节点的引用可以在 ref 的 current 属性中被访问。

const node = this.myRef.current;

ref 的值根据节点的类型而有所不同:

  • ref 属性用于 HTML 元素时,构造函数中使用 React.createRef() 创建的 ref 接收底层 DOM 元素作为其 current 属性。
  • ref 属性用于自定义 class 组件时,ref 对象接收组件的挂载实例作为其 current 属性。
  • 不能在函数组件上使用 ref 属性,因为他们没有实例
为Dom元素添加ref
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
// 创建一个 ref 来存储 textInput 的 DOM 元素
this.textInput = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// 直接使用原生 API 使 text 输入框获得焦点
// 注意:我们通过 "current" 来访问 DOM 节点
this.textInput.current.focus(); }
render() {
// 告诉 React 我们想把 <input> ref 关联到
// 构造器里创建的 `textInput` 上
return (
<div>
<input
type="text"
ref={this.textInput} />
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}

React 会在组件挂载时给 current 属性传入 DOM 元素,并在组件卸载时传入 null 值。ref 会在 componentDidMountcomponentDidUpdate 生命周期钩子触发前更新。

为 class 组件添加 Ref
class AutoFocusTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef(); }
componentDidMount() {
this.textInput.current.focusTextInput(); }
render() {
return (
<CustomTextInput ref={this.textInput} /> );
}
}
posted @   K-L  阅读(98)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示