013.React中事件处理

不废话直接展翅

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!-- 准备好容器 -->
    <div id="test"></div>
    <!-- 引入依赖 ,引入的时候,必须就按照这个步骤-->
    <script type="text/javascript" src="../js/react.development.js"></script>
    <script type="text/javascript" src="../js/react-dom.development.js"></script>
    <script type="text/javascript" src="../js/babel.min.js"></script>
    
    <!--这里使用了babel用来解析jsx语法-->
    <script type="text/babel">
        class Demo extends React.Component{
            /*
            1.通过onXxx属性指定事件处理函数(注意大小写)
                a. React中使用的自定义(合成)事件,而不是使用的原生DOM事件 ——为了更好的兼容性
                b. React中事件是通过事件委托方式处理的(委托给组件最外层的元素)——为了高效
            2.通过event.target得到发生事件的DOM元素——不要过度使用ref
            */
            // React.createRef调用后会返回一个容器
            myRef = React.createRef()
            myRef2 = React.createRef()
            // 展示左侧输入框的数据
            showData=(c)=>{
                alert(this.myRef.current.value)
            }
            showData2=(c)=>{
                alert(this.myRef2.current.value)
            }

            // 当事件绑定在事件源本身时可以不用ref
            showData3=(event)=>{
                alert(event.target.value)
            }
           
            render(){
                return (
                    <div id="test">
                        <input ref={this.myRef} type="text" placeholder="点击提示数据"/>
                        <button onClick={this.showData}>点我啊</button>
                        <input ref={this.myRef2} onBlur={this.showData2} type="text" placeholder="失焦提示数据"/>
                        <input onBlur={this.showData3} type="text" placeholder="失焦提示数据"/>
                    </div>
                )
            }
        }

        ReactDOM.render(<Demo/>,document.getElementById('test'))
    </script>
</body>
</html>
复制代码

总结

1.通过onXxx属性指定事件处理函数(注意大小写)

  • a. React中使用的自定义(合成)事件,而不是使用的原生DOM事件 ——为了更好的兼容性
  • b. React中事件是通过事件委托方式处理的(委托给组件最外层的元素)——为了高效

2.通过event.target得到发生事件的DOM元素(时间绑定在事件源本身)——不要过度使用ref

官网可说了 ref虽好不能贪多

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享