Home  >  Article  >  Web Front-end  >  How to use ref in react

How to use ref in react

藏色散人
藏色散人Original
2020-11-26 10:31:482306browse

How to use ref in react: 1. Use it in the form of callback function, the code is like "export default class UserAdd extends Component{...}"; 2. Use it in the string form, the code is like "export ...".

How to use ref in react

The operating environment of this tutorial: Windows7 system, react16 version. This method is suitable for all brands of computers.

Recommended: "Javascript Basics Tutorial"

Two ways to use ref in react

There are two kinds of ref Usage

  • Callback function form (official recommendation)

  • string form

First type Callback function form

There are three triggering methods for the callback function form

After the component is rendered

After the component is unloaded

After the ref is changed

import React,{Component} from 'react'
export default class UserAdd extends Component{
    constructor(){
        super();
    }
    handleSubmit=()=>{
        let name=this.name.value;
        console.log(name);
    }
    render(){
        return(
            <form onSubmit={this.handleSubmit}>
                <div className="from-group">
                    <label htmlFor="name">姓名</label>
                    <input type="text" className="form-control" ref={ref=>this.name=ref}/>
                </div>
                <div className="from-group">
                    <input type="submit" className="btn btn-primary"/>
                </div>
            </form>
        )
    }
 
}

When using the second string form, use this.refs.string

import React,{Component} from &#39;react&#39;
export default class UserAdd extends Component{
    constructor(){
        super();
    }
    handleSubmit=()=>{
        let name=this.refs.name.value;
        console.log(name);
    }
    render(){
        return(
            <form onSubmit={this.handleSubmit}>
                <div className="from-group">
                    <label htmlFor="name">姓名</label>
                    <input type="text" className="form-control" ref="name"/>
                </div>
                <div className="from-group">
                    <input type="submit" className="btn btn-primary"/>
                </div>
            </form>
        )
    }
 
}

For more programming-related knowledge, please visit: Programming Learning! !

The above is the detailed content of How to use ref in react. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn