[react]12、ref

2021-11-08  本文已影响0人  史记_d5da

1、ref

创建ref可以对原生DOM的操作
创建的方式
1、传入字符串
使用时通过 this.refs.传入的字符串格式获取对应的元素
<h2 ref="titleRef">titleRef标题</h2>
2、传入一个对象
对象是通过 React.createRef() 方式创建出来的;
使用时获取到创建的对象其中有一个current属性就是对应的元素;
this.titleObj = createRef()
<h2 ref={this.titleObj}>函数标题</h2>
3、传入一个函数
该函数会在DOM被挂载时进行回调,这个函数会传入一个 元素对象
<h2 ref={(e) => {this.titleFunc = e}}>函数标题</h2>

import React, { PureComponent, createRef } from 'react'
 class Counter extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {  counter: 0 }
    }
    render() {
        return (
            <div>
                <h2>当前计数器:{this.state.counter}</h2>
                <button onClick={e => this.increment()}>+1</button>
            </div>
        )
    }
    increment() {
        const newData = this.state.counter + 1;
        this.setState({
            counter: newData
        })
    }
}
export default class App extends PureComponent {
    constructor(props) {
        super(props);
        this.titleObj = createRef()
        this.counterRef = createRef()
        this.titleFunc = null;
    }
    render() {
        return (
            <div>
                <h2 ref="titleRef">titleRef标题</h2>
                <h2 ref={this.titleObj}>函数标题</h2>
                <h2 ref={(e) => {this.titleFunc = e}}>函数标题</h2>
                <button onClick={e => this.changeText()}>改变标题</button>
                <hr/>
                <Counter ref={this.counterRef}/>
                <button onClick={e => this.counterClick()}>App内部点击</button>
            </div>
        )
    }
    changeText() {
        // 1、字符串
        this.refs.titleRef.innerHTML = "字符串Hello Ref 好标题"
        // 2、对象方式
        this.titleObj.current.innerHTML = "改变对象文字"
        // 3、函数方式
        this.titleFunc.innerHTML = "函数方式改变对象"
        console.log(this.titleFunc)
    }
    counterClick () {
        this.counterRef.current.increment()
        console.log(this.counterRef)
    }
}

注:
不能在函数组件上使用 ref 属性,因为他们没有实例
但是可以通过 React.forwardRef(hooks相关知识)

2、ref的转发

在开发中我们可能想要获取函数式组件中某个元素的DOM,通过forwardRef高阶函数

const Profile = forwardRef(function(props, ref) {
    console.log(props.name);
    return (<p ref={ref}>Profile</p>)
})
上一篇 下一篇

猜你喜欢

热点阅读