React - 组件之 refs 属性

发布于:2025-02-14 ⋅ 阅读:(122) ⋅ 点赞:(0)

在 React 中,refs 是一种用于访问和与 DOM 元素或组件实例进行交互的方式。通过 refs,可以直接调用子组件或者 DOM 元素的方法,获取其属性或状态。

一、字符串 refs (不推荐)

这种方式现在不推荐使用,因为它可能导致不必要的复杂性和问题:

class MyComponent extends React.Component {
    componentDidMount() {
        console.log(this.refs.myDiv); // 访问 DOM 节点
    }

    render() {
        return (
            <div ref="myDiv">Hello, World!</div>
        );
    }
}

二、回调函数形式的 refs 

使用回调函数形式来创建 refs。与字符串 refs 不同,通过回调 refs 可以灵活地处理附加行为:

在使用回调函数形式的 refs 时,React 会自动调用这个回调函数,并把当前的DOM元素节点作为参数传递过来。

1.内联函数形式

import React,{Component} from "react";

export default class Sum extends Component{
    showData = () => {
        console.log(this.input1);
        console.log(this);
    }
    render() {
        return (
            <div>
                <input ref={(currentNode)=>{this.input1 = currentNode}} type="text" />
                <button onClick={this.showData}>点击提示</button>
            </div>
        )
    } 
}
// 若 ref 回调函数是以内联函数的方式定义的,在更新过程中它会被执行两次
// 第一次传入参数 null,接着第二次会传入参数 DOM 元素
// 因为在每次渲染时会 创建一个新的函数实例,
// 所以React 清空旧的 ref 并且设置新的。
// 通过 将 ref 的回调函数定义成 class 的绑定函数的方式可以避免上述问题,但但大多数情况下无关紧要

2.class 绑定

import React,{Component} from "react";

export default class Sum extends Component{
    showData = () => {
        // console.log(this);
    }
    saveInput = (currentNode) => {
        this.input1 = currentNode;
        console.log(this);
    }
    render() {
        return (
            <div>
                {/* 内联函数形式 */}
                {/* <input ref={(currentNode)=>{this.input1 = currentNode}} type="text" /> */}
                {/* class 绑定形式  */}
                <input ref={this.saveInput} type="text" />
                <button onClick={this.showData}>点击提示</button>
            </div>
        )
    }
}

三、createRef 形式(推荐)

createRef(),这是推荐的方式来创建 refs。它更直观且简单,适合于大多数场景:

import React,{Component} from "react";

export default class Sum extends Component{

    // React.createRef() 调用后可以返回一个容器
    // 该容器可以存储被 ref 所标识的节点
    // 注意:该容器是“专人专用”的,只能存储一个
    myRef = React.createRef()
    myRef2 = React.createRef()

    showData = () => {
        // current 是固定的
        const {current} = this.myRef
        console.log(this.myRef);  // {current: input}
        console.log(this.myRef.current);  //  <input type="text" />
        console.log(current.value); // 返回输入的值
    }
    showData2 = () => {
        alert(this.myRef2.current.value)
    }
    render() {
        return (
            <div>
                <input ref={this.myRef} type="text" /> <br/> <br />
                <input onBlur={this.showData2} ref={this.myRef2} type="text" placeholder="失去焦点提示"/>
                <button onClick={this.showData}>点击提示</button>
            </div>
        )
    }
}

使用 createRef() 可以在整个组件生命周期内重复使用该 ref,this.myRef.current 将指向该节点。

使用 event.target

// 失去焦点展示数据
    showData2 = (event) => {
        console.log(event);
        console.log(event.target);
        alert(event.target.value)
    }
    render() {
        return (
            <div>
                <input ref={this.myRef} type="text" /> <br/> <br />
                <input onBlur={this.showData2} type="text" placeholder="失去焦点提示"/>
                <button onClick={this.showData}>点击提示</button>
            </div>
        )
    }

使用注意事项

  • 避免过度使用 refs: 尽量使用 React 的数据流(state 和 props),refs 只应在需要直接操作 DOM 或组件实例的方法时使用。
  • 不应在渲染中修改 refsrefs 的主要作用是提供对 DOM 的引用,因此不应在 render 方法中修改它们的值。
  • Hooks 中使用 useRef: 在函数组件中,可以使用 useRef 来创建 refs,方法与 createRef 类似,但适合于整个组件的生命周期。

总结

  • 在 React 中,refs 提供了对 DOM 元素的直接访问方式。
  • 可以使用字符串(不推荐)、回调形式和 createRef() 创建 refs。
  • refs 允许调用 DOM 的方法和读取其属性。
  • 在函数组件中使用 useRef 可以实现类似功能。

网站公告

今日签到

点亮在社区的每一天
去签到