简体   繁体   English

为什么 onchange 在 React 与 HTML 上的行为不同

[英]Why onchange behaves differently on React vs HTML

First Example第一个例子

HTML: in the example below the console.log() is triggered when the text box is modified and enter is pressed. HTML :在下面的示例中,console.log() 在文本框被修改并按下回车时被触发。

 <input type="text" onchange="console.log(1)" />

React: in the example below the console.log() is triggered only one time, when page is loaded . React:在下面的示例中,console.log() 仅在页面加载时触发一次。

function App() {
  return (
    <input type="text" onChange={console.log(1)} />
  );
}

export default App;

Second example第二个例子

In this example I wrap the console.log() inside a function.在此示例中,我将 console.log() 包装在 function 中。

HTML: Same as before. HTML:和以前一样。 The console.log() is triggered when the text box is modified and enter is pressed.当文本框被修改并按下回车时触发console.log()。

 <script> const foo = () => {console.log(1)} </script> <input type="text" onchange="foo()" />

React: in the example below the console.log() is triggered on the fly . React:在下面的示例中,console.log() 是即时触发的 Press enter is not needed and every input triggers console.log().不需要按 Enter,每个输入都会触发 console.log()。

function App() {
  const foo = () => {console.log(1)}
  return (
    <input type="text" onChange={foo} />
  );
}

export default App;

This is covered in the React tutorial :这在React 教程中有介绍:

With JSX you pass a function as the event handler, rather than a string.使用 JSX,您可以传递 function 作为事件处理程序,而不是字符串。

When you say onChange={console.log(1)} the JavaScript expression console.log(1) is evaluated immediately (and on every render of the component) and the return value is assigned as the event handler (since the return value from console.log is undefined (which is not a function), this is useless).当你说onChange={console.log(1)}时,JavaScript 表达式console.log(1)立即评估(并且在组件的每次渲染时)并且返回值被分配为事件处理程序(因为返回值来自console.logundefined的(这不是一个函数),这是没用的)。


in the example below the console.log() is triggered on the fly.在下面的示例中,console.log() 是即时触发的。

See the description of onChange in the documentation :请参阅文档中对onChange的描述

We intentionally do not use the existing browser behavior because onChange is a misnomer for its behavior and React relies on this event to handle user input in real time.我们故意不使用现有的浏览器行为,因为 onChange 对其行为的用词不当,而 React 依赖此事件来实时处理用户输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM