找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索本站精品资源

首页 教程频道 查看内容

react中ref怎么用

作者:模板之家 2020-11-26 11:50 377人关注

react中ref的使用方法:1、通过回调函数形式进行使用,代码如“export default class UserAdd extends Component{...}”;2、通过?string形式进行使用,代码如“export...”。

react中ref的使用方法:1、通过回调函数形式进行使用,代码如“export default class UserAdd extends Component{...}”;2、通过string形式进行使用,代码如“export...”。

推荐:《javascript基础教程》

  • 该方法适用于所有品牌电脑。

react中ref的两种使用方法

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怎么用的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章!


路过

雷人

握手

鲜花

鸡蛋
来自: 网络收集

全部回复(0)