美文网首页web前端
react中ref的两种使用方法

react中ref的两种使用方法

作者: 该用户太帅没有设置昵称 | 来源:发表于2017-08-12 11:31 被阅读12372次

ref一共有两种使用方式

  • 回调函数形式(官方推荐)
  • string形式

第一种 回调函数形式

回调函数形式一共有三种触发方式

  • 组件渲染后
  • 组件卸载后
  • ref改变后
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>
        )
    }

} 

第二种 字符串的形式 使用时用this.refs.string

import React,{Component} from 'react'
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>
        )
    }

} 

相关文章

  • react中ref的两种使用方法

    ref一共有两种使用方式 回调函数形式(官方推荐) string形式 第一种 回调函数形式 回调函数形式一共有三种...

  • react源码3 - ref

    ref可以获取dom节点或者react元素的实例,一般有三种使用方法 1. string ref 使用方法就是在r...

  • React中ref的使用

    React中Ref是什么? ref是React提供的用来操纵React组件实例或者DOM元素的接口。 ref的作用...

  • 如何使用React Refs

    如何在React中利用ref以及ref转发,回调ref和HOC React Ref是有用的功能,可作为从父组件中引...

  • React 中 ref 的使用

    ref是reference的简写,它是一个引用,在react中,我们使用ref来操作DOM。 在react中,我们...

  • React学习笔记(三)

    React中的 ref 的使用 ref是一个引用,在React中使用ref来直接获取DOM元素从而操作DOM Re...

  • react-ref

    ref:react对真实dom的引用 ref在reactElement上 ref在react组件上

  • React 中的转发ref

    在 React V16.3� 中react引入了: React.forward((props, ref) => R...

  • React中的Ref

    以获取输入框焦点为例 1、字符串形式 2、React 16.3版本以后,使用React.createRef()方法...

  • react: React.forwardRef

    关键点就是React.forwardRef的API中ref必须指向dom元素而不是React组件。 一、React...

网友评论

    本文标题:react中ref的两种使用方法

    本文链接:https://www.haomeiwen.com/subject/srndrxtx.html