javascript - React onChange 不适用于功能组件内的输入

标签 javascript reactjs react-hooks sweetalert

我已经这样做了一百万次,从来没有遇到过这个问题,我不知道我做错了什么。 我有一个简单的输入字段,并且有一个 amountsetAmount 的钩子(Hook) useState,我正在使用 handleChange 函数来更新此但 handleChange 函数未触发

const CustomAmount = () => {
  const [amount, setAmount] = useState(1);

  const handleChange = (e) => {
    console.log(e); // This is not working either

    setAmount(e.target.value);
  };
  return (
    <div className="custom-amount-container">
      <h4>Enter your desired amount</h4>
      <input
        type="number"
        name="custom-amount"
        data-test="custom-amount-input"
        value={amount}
        onChange={handleChange}
      />
    </div>
  );
};

我尝试将其直接放入 onChange 属性中,但仍然没有运气,而且通常如果 onChange 函数不起作用,它也不会更改值,但在这种情况下输入字段内的值正在更改

我还在 sweetalert 模式中使用这个组件

 const customAmountModal = () => {
    return swal(<CustomAmount />);
  };

最佳答案

我一直在尝试调试封装在 swal 内的组件未调用事件处理程序的原因,但未能成功。因此,根据我有限的理解,此类组件不会触发 React 合成事件,但如果您使用 native DOM 事件,您可以实现相同的功能,如下所示:-

import { useEffect, useRef, useState } from "react";
import swal from "@sweetalert/with-react";
import "./styles.css";

const CustomAmount = () => {
  const [amount, setAmount] = useState(1);
  const inputRef = useRef(null);
  const handleChange = (e) => {
    console.log(e.target.value);
    setAmount(e.target.value);
  };

  console.log("render", amount);

  useEffect(() => {
    inputRef.current.addEventListener("input", handleChange);
  }, []);
  return (
    <div className="custom-amount-container">
      <h4>Enter your desired amount</h4>

      <input
        type="number"
        name="custom-amount"
        data-test="custom-amount-input"
        value={amount}
        ref={inputRef}
      />
    </div>
  );
};

export default function App() {
  const customAmountModal = () => {
    return swal(<CustomAmount />);
  };
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <button onClick={customAmountModal}>Click me</button>
    </div>
  );
}

这里是codesandbox链接 - https://codesandbox.io/s/mystifying-jang-jrgex?file=/src/App.js

仍然想知道为什么React方式不起作用。还没有真正使用过 swal,所以不知道它的用途。

关于javascript - React onChange 不适用于功能组件内的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66373181/

相关文章:

reactjs - 覆盖 MuiContainer 类时如何摆脱 Typescript 类型错误?

javascript - 允许在 Chart.js 的工具提示中显示多个数据属性

javascript - React 出售所有按钮货币

javascript - 使用 useReducer 和 useContext,在分派(dispatch)操作时不会重新呈现组件。如何触发重新渲染?

javascript - 具有明确和更新时间的自定义 Hook 无法按预期工作

javascript - 从顶级 App 类更改 React 上下文

javascript - 如何在ajax之外访问dataTable变量

javascript - 变体数组自定义函数 Google Sheets?例如VBA

javascript - jquery延迟加载插件

javascript - 在 mongoosejs 中取列的总和/平均值