React refs使用


学习视频:https://www.bilibili.com/video/BV1wy4y1D7JT?p=27

一、字符串形式的ref(官方不推荐使用)

    

二、回调函数形式的ref

    

三、createRef

    

 事件处理

通过event.target得到发生事件的DOM元素对象 ——————————不要过度使用ref
        class Demo extends React.Component{
            /* 
                (1).通过onXxx属性指定事件处理函数(注意大小写)
                        a.React使用的是自定义(合成)事件, 而不是使用的原生DOM事件 —————— 为了更好的兼容性
                        b.React中的事件是通过事件委托方式处理的(委托给组件最外层的元素) ————————为了的高效
                (2).通过event.target得到发生事件的DOM元素对象 ——————————不要过度使用ref
             */
            //创建ref容器
            myRef = React.createRef()
            myRef2 = React.createRef()

            //展示左侧输入框的数据
            showData = (event)=>{
                console.log(event.target);
                alert(this.myRef.current.value);
            }

            //展示右侧输入框的数据
            showData2 = (event)=>{
                alert(event.target.value);
            }

            render(){
                return(
                    
this.myRef} type="text" placeholder="点击按钮提示数据"/>    this.showData2} type="text" placeholder="失去焦点提示数据"/> 
) } }