gpt4 book ai didi

reactjs - react 形式不再需要 OnChange 了吗?

转载 作者:行者123 更新时间:2023-12-04 17:37:39 24 4
gpt4 key购买 nike

这只是一个关于 react 的理论问题。

我目前正在学习 ReactJS,它非常好,但我对此感到困惑,希望得到回应。

在我在网上找到的每个教程中(其中大部分已经有几年了,我使用的是 React 16.8,这应该是最新版本),每个人都说使用 onChange 很重要。创建表单组件时。在这些教程中,如果您没有 onChange,您将无法在表单中输入任何内容。事件。

我觉得奇怪的是,我可以输入文本,现在一切正常,无需使用任何 onChange事件。

我的问题是这些:

  • 它仍然是强制性的吗?
  • 使用它是一种好习惯吗?
  • 我应该忽略它并在没有它的情况下编码吗?
  • 最佳答案

    我认为务实的答案是onChange不是必需的,但被认为是最佳实践。使用 React 维护表单状态创建了单一的事实来源,并在以后需要验证时提供帮助。
    查看有关受控组件的 React 文档:

    In HTML, form elements such as <input>, <textarea>, and <select> typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState().

    We can combine the two by making the React state be the “single source of truth”. Then the React component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a “controlled component”.


    Controlled Components Docs

    关于reactjs - react 形式不再需要 OnChange 了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56060394/

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