refs使用方法

 

 

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(){
        this.setState({
            counter: this.state.counter +1
        })
    }

}

    

export default class App extends PureComponent {

    constructor(props){
        super(props)
        this.titleRef = createRef()
        this.counterRef = createRef()
    }
    render() {
        return (
            <div>
                {/* ref="字符串/对象/函数"  */}

                {/* 1 */}
                {/* <h2 ref="titleRef">hello React</h2>  */}

                  {/* 2  对象*/}
                 {/* <h2 ref={this.titleRef}>hello React</h2>    */}

                    {/* 3  函数 */}
                 <h2 ref={arg=>this.titleEl = arg}>hello React</h2>   

                <button onClick={e=>this.changeText()}>改变文本</button>


                <Counter ref = {this.counterRef} />
                {/*  可以获取子组件的方法  */}
                <button onClick={e=>this.appBtnClick()}>App按钮</button>
            </div>
        )
    }

    // 可以获取子组件的方法
    appBtnClick(){
        console.log(this.counterRef.current);
        this.counterRef.current.increment()
    }

    changeText(){ 
        // 1 使用方式一  (不推荐)
        // console.log(this.refs.titleRef);
        // this.refs.titleRef.innerHTML = 'hello Eric'

        // 2 使用方式二 对象 (推荐使用)
        // console.log(this.titleRef.current);
        // this.titleRef.current.innerHTML = 'hello Eric'

        //  2 使用方式三 函数方式
        // console.log(this.titleEl);
        // this.titleEl.innerHTML = 'hello Eric' 

    }
}
posted @ 2021-08-12 14:15  13522679763-任国强  阅读(96)  评论(0)    收藏  举报