当前位置: 首页 > news >正文

react Ref 的基本使用

类组件中使用ref

在类组件中,你可以使用createRef来创建一个ref,并将它附加到DOM元素或类组件实例上。使用ref允许你在类组件中访问和操作特定的DOM元素或类组件实例。

下面是在类组件中使用ref的步骤:

  1. 引入ReactcreateRef
    在类组件文件的顶部,你需要从React中导入ReactcreateRef
import React, { Component, createRef } from 'react';
  1. 创建ref:
    使用createRef来创建一个ref对象。
class MyClassComponent extends Component {constructor(props) {super(props);this.myRef = createRef();}// ...
}

在上面的例子中,我们在类组件MyClassComponent的构造函数中创建了一个ref(myRef)。

  1. 绑定ref到DOM元素或类组件实例:
    将创建的ref(myRef)绑定到你想要引用的DOM元素或类组件实例上。在类组件中,你可以使用ref属性来实现这一点。
class MyClassComponent extends Component {constructor(props) {super(props);this.myRef = createRef();}render() {return <input ref={this.myRef} />;}
}

在上面的例子中,我们将ref(myRef)绑定到了一个input元素上。

  1. 在类组件中使用ref:
    现在,你可以在类组件的其他方法中通过this.myRef.current来访问和操作引用的DOM元素或类组件实例。
class MyClassComponent extends Component {constructor(props) {super(props);this.myRef = createRef();}handleButtonClick = () => {if (this.myRef.current) {this.myRef.current.focus();}};render() {return (<div><input ref={this.myRef} /><button onClick={this.handleButtonClick}>Focus Input</button></div>);}
}

在上面的例子中,我们创建了一个按钮点击事件handleButtonClick,当按钮被点击时,会调用this.myRef.current.focus()来将焦点设置到input元素上。

通过这种方式,你可以在类组件中使用ref来引用和操作特定的DOM元素或类组件实例。

hooks组件中使用ref

在 React Hooks 组件中,你可以使用useRef来创建并使用 ref。useRef是一个 Hooks 函数,它允许你在函数组件中保持可变的数据,类似于在类组件中使用实例属性。ref 在许多情况下很有用,例如访问 DOM 元素、存储任意值等。

使用useRef的步骤如下:

  1. 引入useRef
    在组件文件中,首先需要从 React 中导入useRef
import React, { useRef } from 'react';
  1. 创建 ref:
    使用useRef来创建一个 ref 对象:
const myRef = useRef(initialValue);

其中,initialValue是 ref 的初始值。

  1. 将 ref 绑定到 DOM 元素:
    myRef绑定到你想要引用的 DOM 元素上。这通常通过在 JSX 中的ref属性中传递myRef来实现:
<input ref={myRef} />
  1. 在组件中使用 ref:
    你可以在组件中通过myRef.current来访问 ref 的当前值。这是一个可变的对象,可以用于存储和读取任何数据。
const MyComponent = () => {const inputRef = useRef(null);const handleButtonClick = () => {if (inputRef.current) {inputRef.current.focus();}};return (<div><input ref={inputRef} /><button onClick={handleButtonClick}>Focus Input</button></div>);
};

在上面的例子中,我们创建了一个 input 元素的 ref,并在按钮点击事件中使用inputRef.current.focus()来将焦点设置到 input 元素上。

需要注意的是,useRef返回的myRef.current属性在组件的整个生命周期中保持不变,但是其内部的值可以在不重新渲染组件的情况下发生变化。这使得useRef适用于存储在组件渲染期间需要跨渲染保持不变的数据。

自定义组件ref

当你在React中创建自定义组件时,如果想在父组件中使用ref引用子组件,你需要使用forwardRef方法。forwardRef允许你将ref从父组件传递到子组件中。

下面是使用forwardRef的步骤:

  1. 在子组件中使用forwardRef方法:
    在子组件中使用forwardRef方法来传递ref,并将它与子组件的DOM元素或其他需要引用的元素绑定起来。同时,确保在组件定义中的第二个参数(通常称为ref)中接收传递的ref。
import React, { forwardRef } from 'react';const CustomChildComponent = forwardRef((props, ref) => {return <input ref={ref} />;
});

在上面的例子中,我们创建了一个名为CustomChildComponent的自定义子组件,并在其中使用forwardRef来传递ref参数,并将它绑定到了input元素上。

  1. 在父组件中使用ref:
    现在,你可以在父组件中使用CustomChildComponent并将一个ref传递给它。这样,父组件就可以引用子组件内部的input元素。
import React, { useRef } from 'react';
import CustomChildComponent from './CustomChildComponent';const ParentComponent = () => {const inputRef = useRef(null);const handleButtonClick = () => {if (inputRef.current) {inputRef.current.focus();}};return (<div><CustomChildComponent ref={inputRef} /><button onClick={handleButtonClick}>Focus Input</button></div>);
};

在上面的例子中,我们在父组件中创建了一个ref(inputRef),并将它传递给CustomChildComponent作为ref属性。现在,我们可以在handleButtonClick函数中使用inputRef.current.focus()来将焦点设置到子组件中的input元素上。

通过这样的方法,你就可以在自定义组件中使用ref,并从父组件中控制子组件内部的DOM元素或组件实例。

自定义Hooks组件想向外暴露一些方法

如果你希望自定义组件使用ref时向外暴露一些方法,可以通过在子组件内部创建一个ref,并将它与需要暴露的方法关联。然后,将这个ref作为一个对象,包含暴露的方法,传递给父组件。这样,父组件就可以通过ref调用子组件暴露的方法。

下面是一个示例:

  1. 子组件中创建ref和暴露方法:
import React, { forwardRef, useRef, useImperativeHandle } from 'react';const CustomChildComponent = forwardRef((props, ref) => {const inputRef = useRef(null);// 暴露给父组件的方法const focusInput = () => {if (inputRef.current) {inputRef.current.focus();}};// 使用 useImperativeHandle 将方法暴露给父组件useImperativeHandle(ref, () => ({focusInput: focusInput}));return <input ref={inputRef} />;
});

在上面的例子中,我们创建了一个ref(inputRef)来引用input元素,并定义了一个focusInput方法用于将焦点设置到input元素上。然后,我们使用useImperativeHandlefocusInput方法暴露给父组件。

  1. 在父组件中使用子组件的暴露方法:
import React, { useRef } from 'react';
import CustomChildComponent from './CustomChildComponent';const ParentComponent = () => {const childComponentRef = useRef(null);const handleButtonClick = () => {if (childComponentRef.current) {childComponentRef.current.focusInput();}};return (<div><CustomChildComponent ref={childComponentRef} /><button onClick={handleButtonClick}>Focus Input</button></div>);
};

在上面的例子中,我们在父组件中创建了一个ref(childComponentRef),并将其传递给CustomChildComponent。在父组件中的handleButtonClick函数中,我们可以通过childComponentRef.current.focusInput()调用子组件中暴露的focusInput方法,将焦点设置到子组件的input元素上。

通过这种方式,你可以在自定义组件中使用ref,并将一些方法暴露给父组件,使父组件可以调用子组件的特定功能。

http://www.lryc.cn/news/113372.html

相关文章:

  • 宝塔面板点击SSL闪退打不开怎么解决?
  • 如何将安卓 Gradle 模块打包发布到本地 Maven 仓库
  • 【Docker】Docker比虚拟机快的原因、ubuntu容器、镜像的分层概念和私有库的详细讲解
  • java.lang.IllegalArgumentException: Invalid character found in methodname
  • 【PCB专题】Allegro高速电路Xnet网络等长约束——SDIO信号为例
  • leetcode每日一练-第278题-第一个错误的版本
  • 最小生成树笔记(Prim算法Kruskal算法)
  • 4、数据清洗
  • Python-OpenCV 图像的基础操作
  • test111
  • 17. Spring 事务
  • 【C# 基础精讲】运算符和表达式
  • 【搜索】DFS连通性模型
  • 项目优化后续 ,手撸一个精简版VUE项目框架!
  • 【深度学习笔记】TensorFlow 基础
  • 面试题-springcloud中的负载均衡是如何实现的?
  • flink的ProcessWindowFunction函数的三种状态
  • day50-springboot+ajax分页
  • Win7 专业版Windows time w32time服务电脑重启后老是已停止
  • 全网最强,接口自动化测试-token登录关联实战总结(超详细)
  • OLAP ModelKit Crack,ADO.NET和IList
  • 4 三组例子,用OpenCV玩转图像-AI-python
  • 计算机网络-三种交换方式
  • 03 制作Ubuntu启动盘
  • 【JavaSE】String类中常用的字符串方法(超全)
  • Bootload U-Boot分析
  • 以公益之行,筑责任之心——2023年中创算力爱心公益助学活动
  • 【机器学习】处理样本不平衡的问题
  • Android前沿技术?Jetpack如何?
  • 为react项目添加开发/提交规范(前端工程化、eslint、prettier、husky、commitlint、stylelint)