gl0*_*l03 6 javascript html-input dom-events preventdefault reactjs
我刚刚发现一个流浪者event.preventDefault()
正在破坏我的复选框处理onChange
程序:
import { Component } from 'react';
class App extends Component {
constructor(props) {
super(props)
this.state = {
accepted: false
}
}
changeChecked = (event) => {
this.setState((state) => ({
accepted : !state.accepted
}));
event.preventDefault(); // <- this very bad
}
render() {
return (
<input
type="checkbox"
onChange={this.changeChecked}
checked={this.state.accepted}
/>
);
}
}
export default App;
Run Code Online (Sandbox Code Playgroud)
第一次单击时产生的行为是正确更新的状态,但复选框仅在下一次重新渲染时更改为其“选中”外观,例如。第二次点击。
这是为什么?受控组件独立于浏览器事件工作不是重点吗?
有人向我解释这一点肯定会减轻我花费数小时来简化复杂用例的痛苦。谢谢你!
更新:这是一个快速的Codepen 示例,演示了奇怪的行为。我添加了一个“未阻止的复选框”和一个包含已阻止onClick
事件的复选框作为比较。onChange
请注意,当我单击另一个复选框时,带有阻止的复选框如何将其外观切换为实际状态。
小智 4
复选框的行为略有不同。您可能知道,典型的用例preventDefault()
是onSubmit()
function of a form where you will do your own AJAX call, and thus want to prevent the default form submission. But with checkboxe (and most inputs) there\'s a little more involved.
Per MDN, the checked
attribute is "A Boolean attribute indicating whether or not this checkbox is checked by default (when the page loads). It does not indicate whether this checkbox is currently checked: if the checkbox\xe2\x80\x99s state is changed, this content attribute does not reflect the change." In a funny way then, there\'s a disconnect between the checked
attribute, and whether or not the state of the input is checked or not. When it comes to React, on each rerender, the checked
attribute will reflect the current state, but it\'s still only a default value in the sense that the input has been newly rendered, and not manipulated since the state last changed.
eventListener
for <input type="checkbox" />
Also, without getting too off track, the event that natively changes the state on a checkbox input is actually the click
event, not the change
event. If you were to mess with the listeners and the values of a checkbox input in your browser\'s js console, you\'d see you could manipulate it in a way that the checkbox isn\'t checked, but the values of the node say otherwise.
Based on the above, in this case you don\'t want to prevent the default behavior, because the default behavior on the change
event doesn\'t conflict with what you want to do (and for some reason preventing it causes problems). In fact, in the Mozilla docs examples, you\'ll notice they don\'t use preventDefault()
when updating state on controlled components. I wish I had a better understanding of exactly why adding preventDefault()
to change handlers for inputs causes problems like this, but hopefully these few little tidbits give some more clarity.
归档时间: |
|
查看次数: |
4945 次 |
最近记录: |