refs转发

ref 转发不但可以转发指向具体的dom组件,也可以指向class组件的实例
import React from 'react'
import ReactDOM from 'react-dom';

//ref 转发不但可以转发指向具体的dom组件,也可以指向class组件的实例
class Button extends React.Component{
    constructor(props){
        super(props);
        this.handClick = this.handClick.bind(this);
        this.ccref = React.createRef();
    }
    handClick(){
        alert('我是事件')
    }
    render(){
        return (
            <button ref={this.ccref}></button>
        )
    }
}

const Input = React.forwardRef((props,ref)=>{
    return (
        <div>
            <Button ref={ref} />
            <button>点击我</button>
        </div>
    )
})



class App extends React.Component{
    constructor(props){
        super(props);
        this.cref = React.createRef();
    }
    componentDidUpdate(prevProps){

    }
    componentDidMount(){
    //this.cref指向的是class button组件的实例   console.log(this.cref.current.ccref) console.log(this.cref.current.handClick()) } render(){ return ( <Input ref={this.cref} /> ) } } ReactDOM.render(<App />,document.getElementById('root'));

 

import { extend } from 'lodash';
import React, { useEffect, useRef, useState } from 'react'
import ReactDOM from 'react-dom';

function usePrevious(count){
    const iref = useRef();
    useEffect(() => {
        iref.current = count;
    });
    return iref.current
}

//如何获取上一轮的props或state
//这就说明ref的值改变并不会通知到我们不会使组件重新渲染
function App(){
    const [count,setCount] = useState(0);
    const prevCount = usePrevious(count);
    const countRef = useRef();
    //解决这个问题你可以手动创建个ref 保存他修改他并读取他
    //除非你正在做懒加载否则不要在渲染阶段去设置refs  你应该在事件处理函数或者是useeffect中去设置refs
    //如果想要在异步的回调中获取最新的state 你可以手动创建个ref 用来保存他 修改他  并读取他
    function handleClick(){
        setTimeout(() => {
            alert(countRef.current)
        }, 3000);
    }
    useEffect(() => {
        countRef.current = count
    });
    return (
        <div>
            {count}-上一个值:{prevCount}
            <button onClick={()=>setCount(count+1)}>
                点击我
            </button>
            <button onClick={handleClick}>show alert</button>
        </div>
    )
}

ReactDOM.render(<App />, document.getElementById('root'));

  

posted @ 2022-06-11 22:07  飞奔的龟龟  阅读(82)  评论(0)    收藏  举报