ref useRef React.createRef React.forwardRef

ops/2025/1/14 19:06:52/

react如何获取真实DOM:useRef, React.CreateRef()

access DOM nodes directly within React:ref.current

Let’s say you want to change the value of an <input> element, but without using props or re-rendering the whole component. They’re an excellent way to update part of a component without the need to re-render the entire thing. 


1. useRef

const {useRef} = React


const App=()=>{

    const buttonRef=useRef();

    return(

    <button

        onClick={()=>{console.log(buttonRef.current);}}

        ref={buttonRef} >

        Special Button

    </button>

    );

}


2. React.createRef()

create a ref by calling React.createRef() and attaching a React element to it using the ref attribute on the element.

class Example extends React.Component { 

constructor(props) { 

    super(props) 

    this.exampleRef = React.createRef() // Create the ref 

render() { 

 return ( 

 <div> 

    //这里是uncontrolled form

     <input type="text" ref={this.exampleRef} /> // Call the ref with the `ref` attribute

</div> 

}}


3. Passing a callback function to ref

create a ref by passing a callback function to the ref attribute of a component. 

<input type="text" ref={element=>this.textInput=element}/>

The callback is used to store a reference to the DOM node in an instance property. When we want to make use of this reference, we access it using: this.textInput.value

When you make use of callback like we did above, React will call the ref callback with the DOM node when the component mounts, when the component un-mounts, it will call it with null.

class App extends React.Component { 

    state = { value: '' }

    handleSubmit = e => { 

    e.preventDefault();    

    this.setState({ value: this.textInput.value})  

};  

render() {    

    return (      

    <div>   

        <h3>Value: {this.state.value}</h3>        

        <form onSubmit={this.handleSubmit}>          

        <input type="text" ref={element => this.textInput = element} />          

        <button>Submit</button>        

    </form>      

</div>    

);  }}


4. pass ref from a parent component to a child component using callbacks.

child:

const Input = props =>{

    return(

//This component is expecting inputRef props from its parent component which is then used to create a ref to the DOM node.

        <inputtype="text" ref={ props.inputRef }/>

    );

};

parent:

In the App component, we want to obtain the text that is entered in the input field (which is in the child component) so we can render it. The ref is created using a callback like we did in the first example of this section. The key lies in how we access the DOM of the input element in the Input component from the App component. If you look closely, we access it using this.inputElement. So, when updating the state of value in the App component, we get the text that was entered in the input field using this.inputElement.value.

class App extends React.Component{

    state={

        value:""

    };

    handleSubmit=event=>{

        this.setState({ value:this.inputElement.value });

    };

    render() {

        return(

            <div>

                <h3>Value: {this.state.value}</h3>

                <Input inputRef={el=>(this.inputElement=el)}/>

                <button onClick={this.handleSubmit}>Submit</button>

    </div>

);}}


5. Forwarding a ref from one component to another

Ref forwarding is the technique of passing a ref from a component to a child component by making use of the React.forwardRef() method.

child: 

const Input=React.forwardRef((props,ref)=>(

    <inputtype="text"ref={ref}/>

));

parent:

class App extends React.Component{

    constructor(props) {

        super(props)

        this.inputRef=React.createRef();

        this.state={value:''}

    }

    handleSubmit=e=>{

        e.preventDefault();

        this.setState({value:this.inputRef.current.value})

    };

    render() {

        return(

            <div>

                <h3>Value: {this.state.value}</h3>

                <form onSubmit={this.handleSubmit}>

                    <Input ref={this.inputRef}/>

                    <button>Submit</button>

                </form>

            </div>

);}}


uncontrolled form example: Using ref for form validation

class App extends React.Component { 

    constructor(props) { 

        super(props); 

         this.username = React.createRef(); 

         this.password = React.createRef(); 

         this.state = { 

             errors: [] 

         }; 

 } 

     handleSubmit = (event) => { 

         event.preventDefault(); 

         const username = this.username.current.value; 

         const password = this.password.current.value; 

         const errors = this.handleValidation(username, password); 

         if (errors.length > 0) { 

             this.setState({ errors }); 

             return; 

             } 

             // Submit data 

     }; 

    handleValidation = (username,password) => { 

        const errors = []; 

        if (username.length === 0) { errors.push("Username cannot be empty"); } 

        if (password.length < 6) { errors.push("Password should be at least 6 characters long");}   

         return errors;  

    };  


render() {    

    const { errors } = this.state;    

    return (      

    <form onSubmit={this.handleSubmit}>          

        {errors.map(error => <p key={error}>{error}</p>)}          

        <input type="text" ref={this.username} />          

        <input type="text" ref={this.password} /> 

        <button>Submit</button>         

 </form>      

);}}


访问节点的情况


将节点绑定在this.input属性上


dom api:focus


无状态
最后编辑于:2025-01-11 21:04:55


喜欢的朋友记得点赞、收藏、关注哦!!!


http://www.ppmy.cn/ops/150078.html

相关文章

PyCharm 的安装与使用(Window)

1 PyCharm 简介 PyCharm 是一款由 JetBrains 公司开发的专门用于 Python 语言开发的集成开发环境&#xff08;IDE&#xff09;。以下是其相关介绍&#xff1a; 1.1 特点与功能 智能代码编辑&#xff1a;提供高度智能化的代码编辑器&#xff0c;支持语法高亮、自动补全、代码重…

四阶龙格库塔法求解二元二阶常微分方程

龙格库塔法&#xff08;Runge-Kutta methods&#xff09;是用于非线性常微分方程的解的重要的一类隐式或显式迭代法。在工程领域应用广泛&#xff0c;可用于求解复杂系统的运动方程等问题。 这里采用matlab程序编写代码实现龙格库塔法对于二元二阶常微分方程的求解。 例 { x …

Qt重写webrtc的demo peerconnection

整个demo为&#xff1a; 可以选择多个编码方式&#xff1a; cmake_minimum_required(VERSION 3.5)project(untitled LANGUAGES CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_INCLUDE_CURRENT_DIR ON)set(CMAKE_AUTOUIC ON) set(CMAKE_AUTOMOC ON) set(CMAKE_AUTORCC ON)set(CMA…

leetcode - 916. Word Subsets

Description You are given two string arrays words1 and words2. A string b is a subset of string a if every letter in b occurs in a including multiplicity. For example, “wrr” is a subset of “warrior” but is not a subset of “world”. A string a from …

如何将 sqlserver 数据迁移到 mysql

文章目录 前言一、导出SQL Server 数据二、转换数据格式为MySQL兼容格式三、导入数据到MySQL数据库五、使用ETL工具六、通过 navicat 工具七、总结 前言 将 SQL Server 数据迁移到 MySQL 是一个常见的数据库迁移任务&#xff0c;通常涉及以下几个关键步骤&#xff1a;导出 SQL…

Pycharm 使用教程

一、基本配置 1. 切换Python解释器 pycharm切换解释器版本 2. pycharm虚拟环境配置 虚拟环境的目的&#xff1a;创建适用于该项目的环境&#xff0c;与系统环境隔离&#xff0c;防止污染系统环境&#xff08;包括需要的库&#xff09;虚拟环境配置存放在项目根目录下的 ven…

鸿蒙面试 2025-01-11

ArkTs 和TS的关系&#xff1f; ArkTS&#xff08;方舟开发语言&#xff09;与 TypeScript&#xff08;TS&#xff09;存在紧密联系&#xff0c;同时也有显著区别&#xff1a; 联系 语法基础&#xff1a;ArkTS 在语法层面大量借鉴了 TypeScript &#xff0c;TypeScript 里诸如…

蓝桥杯历届真题 #食堂(C++,Java)

这题没什么好说的 考虑所有情况然后写就完了 虽然赛场上 交完不知道答案(doge) 原题链接 #include<iostream>using namespace std;int main() {int n;cin >> n;//能优先安排6人桌,要先安排6人桌//6人桌可以是222 或者 33 或者42//优先用33组合,因为3人寝只能凑6人…