react中事件冒泡之填坑
阿新 • • 發佈:2018-07-04
app 簡單 冒泡 wrapper change checked 執行 class 讓我
今天在寫個組件,大致代碼是這樣的:
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;
就可以了。
問題雖簡單,但還是讓我懵逼了一會,在此處記錄下來長個記性
react中事件冒泡之填坑