React之ref的使用

一、React.creactRef()
在dom元素上使用createRef

constructor(){
        super()
        //创建一个ref的引用
        this.textInput = React.createRef();
 }
render(){
	return{
	//在DOM中使用ref
		<input ref={this.textInput} type="text"></input>
	}
}

在类组件上使用createRef

//父组件
export default class AutoFocusTextInput extends React.Component {
    constructor() {
        super()
        //第一步:创建ref
        this.textInput = React.createRef();
    }

    //组件挂载完毕
    componentDidMount() {
        //this.textInput.current 其实就是TextInput组件对象
        //现在我们要做的事情就是让TextInput组件中的input文本框自动获取焦点
        // console.log(this.textInput.current)
        //调用子组件对象的focusInputText()方法
        this.textInput.current.focusInputText()
    }

    render() {
        return (<div>
            AutoFocusTextInput
            {/*在使用子组件的时候,通过ref来引用组件对象,此时this.textInput代表子组件*/}
            <TextInput ref={this.textInput}></TextInput>
        </div>)
    }
}
//子组件
class TextInput extends React.Component {
    constructor() {
        super()
        this.input = React.createRef();
    }

    //该方法的目的就是让input文本框获取焦点
    focusInputText = () => {
        this.input.current.focus();
    }

    render() {
        return (<div>
            <input ref={this.input} type="text"></input>
        </div>)
    }
}

二、ref回调
基本使用

//第一种方法,在构造函数中创建ref
constructor() {
        super()

        this.setInputRef = (element) => {
            this.input = element;
        }
 }
				{/*通过回调函数的方式指定ref*/}
                <input
                    type="text"
                    ref={this.setInputRef}
                />
{/*第二种方法:直接入参回调函数的方式指定ref*/}
                <input
                    type="text"
                    ref={(element) => { this.input2 = element }}
                />

父子组件传递回调函数ref

import React from 'react'
//子组件
function CustomTextInput(props) {
    return (<div>
        <input ref={props.inputRef}></input>
    </div>)
}
//父组件
export default class PassCallBackRef extends React.Component {
    constructor() {
        super()
    }

    clickHandler = ()=>{
        console.log(this.input.value,"子组件input的数据")
    }

    render() {
        return (
            <div>
                {/*父组件中使用子组件的时候传递了一个inputRef属性,但是这个属性值是一个回调函数的ref,在孩子中使用了这个回调函数ref
                此时就相当于父亲的this.input引用了孩子的input元素
                */}
                <CustomTextInput inputRef={el => { this.input = el }}></CustomTextInput>
                <button onClick={this.clickHandler}>点我获取数据</button>
            </div>
        )
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42944436/article/details/105057181
今日推荐