React的onChange事件支持冒泡

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>

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

posted @   全玉  阅读(159)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2018-09-23 webpack css压缩方案
2018-09-23 js空对象判断 isPlainObject
2018-09-23 sourcemap总结
点击右上角即可分享
微信分享提示