gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:06:11 25 4
gpt4 key购买 nike

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

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