gpt4 book ai didi

javascript - 在 React 中使用 onClick 处理程序输入?

转载 作者:行者123 更新时间:2023-12-04 09:48:18 26 4
gpt4 key购买 nike

由于 change 事件仅在某些浏览器(即 IE)中仅在失去焦点时才会为 input 触发,我的理解是 click 事件是监听变化的更好方法(参见 Getting value of HTML Checkbox from onclick/onchange events )。

但是,当我仅向 react input 元素提供带有 onClick 处理程序的 checked 属性时,它提示:

Warning: Failed prop type: You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.

这里的解决方案是什么? react 文档似乎建议使用 onChange,但这与上面列出的答案中的建议相冲突。

最佳答案

React 提供了一个名为 SyntheticEvent 的跨浏览器包装器为事件提供规范化接口(interface),但文档没有明确说明哪些情况已处理或未处理。关于 IE 的边缘情况,this Github comment从 2015 年开始表明它已经得到处理:

... react uses the native click event to listen to user interaction with the radio, and then calls the onchange for the input. The reason for this (at least according to the comment in the code) is because IE8 does not fire the change event until blur, so in order to be 'compatible' with IE8, the click event is used.

查看React's source ,对我来说,情况确实如此:

function shouldUseClickEvent(elem) {
// Use the `click` event to detect changes to checkbox and radio inputs.
// This approach works across all browsers, whereas `change` does not fire
// until `blur` in IE8.
const nodeName = elem.nodeName;
return (
nodeName &&
nodeName.toLowerCase() === 'input' &&
(elem.type === 'checkbox' || elem.type === 'radio')
);
}

所以我会像在现代浏览器上那样使用 onChange ,如果你发现 IE 上的行为不同,我会担心自己做(或者甚至在 React 的 repo 中打开一个新问题) .

关于javascript - 在 React 中使用 onClick 处理程序输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62050295/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com