事件处理

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

    1. React使用的是自定义(合成)事件, 而不是使用的原生DOM事件,比如onclickonClick;为了更好的兼容性

    2. React中的事件是通过事件委托方式处理的(委托给组件最外层的元素),也就是事件冒泡,比如给ul设置onclick事件就等同于给每个li设置了事件,为了高效

  2. 通过event.target得到发生事件的DOM元素对象

    class Bt extends React.Component {
    
        contentRef = React.createRef()
    
        render() {
            return (
                <div>
                    <input type="text" ref={this.contentRef}/>
                    <button onClick={this.sayHello}>获取内容</button>
                </div>
            );
        }
    
        sayHello = (event) => {
            console.log(event.target); // 这个就是button按钮
            console.log(this.contentRef);
            alert(this.contentRef.current.value);
        }
    }

最后更新于