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

React onChange not working for input inside functional component

我已经做了一百万次了,从来没有遇到过这个问题,我不知道我做错了什么。 我有一个简单的输入字段并且有一个 amountsetAmount 的钩子 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 modal

中使用这个组件
 const customAmountModal = () => {
    return swal(<CustomAmount />);
  };

我一直在尝试调试事件处理程序未被包裹在 swal 内但无法调用的组件的原因。因此,根据我有限的理解,React Synthetic Events 不会被此类组件触发,但如果您使用 Native DOM Events,您可以像这样实现相同的功能:-

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 link - https://codesandbox.io/s/mystifying-jang-jrgex?file=/src/App.js

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

你也可以这样做

onChange={e => setAmount(e.target.value)

这是目前 swal 和 React 17 的一个已知问题: https://github.com/t4t5/sweetalert/issues/950

作者知道并表示他会尽快推送更新。

随时 upvote/watch 这个问题的更新。

这是因为 SyntheticEvent 对象被合并了。这意味着 SyntheticEvent 对象将被重用,并且在调用事件处理程序后所有属性都将被取消。

现在您正在重用事件对象,首先是 console.log 函数,然后是 setState。

https://reactjs.org/docs/legacy-event-pooling.html