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

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

猜你喜欢

转载自www.cnblogs.com/clover77/p/9264472.html