React的onChange事件支持冒泡

发布时间 2023-09-23 10:29:53作者: 看风景就

React的合成事件,所有事件都冒泡到document,带来的一个方便的地方就是,原本原生事件不支持冒泡的,在React中都支持冒泡

例如 focus,blur,change,submit,reset,select 等事件不支持冒泡,

但是在 React中,可以使用同名的合成事件来支持冒泡,这样可以带来一个好处,减少事件挂载


例如 对 radio 组挂载change事件

在原生 html 中,应该是这样

<div>
    <label className="rd"><input type="radio" value="1" name="gender" onchange="getValue(this)" /> Male </label>
    <label className="rd"><input type="radio" value="2" name="gender" onchange="getValue(this)" /> Female </label>
    <label className="rd"><input type="radio" value="3" name="gender" onchange="getValue(this)" /> Other </label>
</div>

要挂载多次onchange事件

当然,使用js或jquery可能会省点事

//js必须使用forEach,不能直接对集合绑定事件
var radios = document.querySelectorAll('input[type=radio][name="gender"]');
radios.forEach(radio => radio.addEventListener('change', () => alert(radio.value)));

//jquery可以对集合绑定事件
$('input[type=radio][name="gender"]').on('change', function() {
    alert(this.value);
});

而在React中,可以直接在父元素上挂载onChange事件,简化代码

<div onChange={this.onChangeValue}>
    <label className="rd"><input type="radio" value="1" name="gender" /> Male </label>
    <label className="rd"><input type="radio" value="2" name="gender" /> Female </label>
    <label className="rd"><input type="radio" value="3" name="gender" /> Other </label>
</div>

此思路可以扩展,用以处理其他问题,待补充