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; 就可以了。

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

  • 相关阅读:
    龙果支付系统
    Java并发多线程
    StringRedisTemplate常用操作
    统一支付平台转型
    IntValue()方法 和 ValueOf()方法
    Java中一些知识的归纳总结
    mybatis的一些特殊符号标识(大于,小于,等于,不等于)
    MySQL中大于等于小于等于的写法
    boost::bind应用示例
    VC除零异常(错误)捕获
  • 原文地址:https://www.cnblogs.com/clover77/p/9264472.html
Copyright © 2011-2022 走看看