zoukankan      html  css  js  c++  java
  • react中事件冒泡之填坑

    今天在写个组件,大致代码是这样的:

    class Switch extends React.Component {
        handlerChange = (e) => {
            const {onChange} = this.props;
            onChange && onChange(e);
        }
        render(){
            const {checkedLabel, uncheckedLabel, small, ...others} = this.props;
            const isSmall = size === 'small';
            return (
                <span
                    className="wrapper"
                    {...otners}
                >
                    {!isSmall && checked && checkedLabel ? <span className={`${prefix}-label`}>{checkedLabel}</span> : null}
                    {!isSmall && !checked && uncheckedLabel ?
                        <span className={`${prefix}-label`}>{uncheckedLabel}</span> : null}
                    <input type="checkbox" onChange={this.handlerChange} checked/>
                </span>
            );
        }
    }
    

    下面是该组件的业务应用场景:

    class App extends React.Component {
        onChange = (e) => {
            console.log(e);
        }
        render(){
            return (
                <Switch 
                    onChange={this.onChange}
                    checkedLabel="已开启"
                    uncheckedLabel="已关闭"
                />
            );
        }
    }
    

    运行代码,明明点击了一次,switch组件的handlerChange执行了一次,但是App的onChange执行了2次!!!

    最后发现,原来是input的onChange事件向上冒泡,冒到了span.wrapper上,而我在const {checkedLabel, uncheckedLabel, small, ...others} = this.props;中并未将onChange过滤掉。

    解决办法很简单,将这行代码改成 const {checkedLabel, uncheckedLabel, small, onChange ...others} = this.props; 就可以了。

    问题虽简单,但还是让我懵逼了一会,在此处记录下来长个记性

  • 相关阅读:
    codeforces 733D
    HDU2647
    匈牙利算法 DFS模板(了解度+1)
    HDU1532 网络流:最大流之福德福克森算法
    mysql5 解压版 安装 建用户授权采坑
    Spring Boot 相关随笔
    Spring Boot 项目jar包 构建运行
    随笔小结
    war包 jar包理解(记录)
    vue axios异步请求及回调函数(前台)
  • 原文地址:https://www.cnblogs.com/clover77/p/9264472.html
Copyright © 2011-2022 走看看