【问题标题】:getting error React does not recognize the `handleChange` prop on a DOM element出现错误 React 无法识别 DOM 元素上的 `handleChange` 道具
【发布时间】:2020-03-23 06:07:14
【问题描述】:

我正在尝试让一个 login form 做出反应。但我收到了这个错误

React 无法识别 DOM 元素上的 handleChange 属性。如果您有意希望它作为自定义属性出现在 DOM 中,请将其拼写为小写 handlechange

输入值也没有设置输入字段当我输入input字段时它没有更新状态为什么?

这是我的代码 https://codesandbox.io/s/quirky-clarke-qbkjw

<form noValidate>
      <TextBox
        label="Username"
        name="username"
        type="text"
        helperText="Assistive text"
        handleChange={handleChange}
        handleMouseDownPassword={handleMouseDownPassword}
        value={userId}
      />
      <TextBox
        label="Password"
        name="password"
        type="password"
        helperText="Assistive text"
        value={password}
        showPassword={showPassword}
        handleChange={handleChange}
        handleClickShowPassword={handleClickShowPassword}
        handleMouseDownPassword={handleMouseDownPassword}
      />
      <div className="button-group">
        <button>LOGIN</button>
      </div>
    </form>

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    TextBox 组件中,您将通过{...props} 传递来自父级的所有道具。考虑到 TextField 本身没有 handleChange 属性,我假设它会将其传递给底层输入 DOM 元素,该元素无法识别该属性。

    您可以做的是提取 TextBox 中使用的道具并使用 rest 参数收集其余部分,因此您最终不会传递不必要的道具:

    export default function TextBox({handleChange, handleClickShowPassword, handleMouseDownPassword, value,  ...props}) {
    

    另一种选择是从 TextField 组件中删除 {...props} 并显式传递所有必要的道具。

    Updated Sandbox

    【讨论】:

    • 但是输入字段中没有设置值,为什么 //?
    • 无论我输入什么都没有反映
    • ...!!请参阅 his synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property nativeEvent` 关于已发布/无效的合成事件。这设置为空。如果您必须保留原始合成事件,请使用 event.persist()。 `
    • 当我尝试在文本字段中输入任何内容时收到此警告
    • 文本字段值未更新
    【解决方案2】:

    React 不喜欢道具名称中的大写字母。而不是传递“handleChange”,而是传递“handlechange”。 “handleMouseDownPassword”会出现类似的错误。

    关于输入问题,我认为您没有提供足够的上下文。但是你必须有一个 handleChange 方法来在每次更改字段时更新状态。

    【讨论】:

      【解决方案3】:

      我改了handleChange()函数,你只是设置VALUE状态,你需要在第一次输入时设置状态userId,在第二次输入时设置密码输入

      在 b.js 添加 props name={stateName} 以便 handleChange() 知道哪个输入在控制

      查看演示了解更多信息: https://codesandbox.io/s/gracious-heisenberg-z4q4z

      (其他答案解释了为什么您在控制台中收到该错误 ...props)

      【讨论】:

        猜你喜欢
        • 2020-02-16
        • 2019-05-19
        • 2020-09-02
        • 2018-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-18
        相关资源
        最近更新 更多