如何解决反应 onChange 不适用于功能组件内的输入
我已经做了一百万次,从来没有遇到过这个问题,我不知道我做错了什么。
我有一个简单的输入字段,有一个 useState
和 amount
的钩子 setAmount
,我正在使用 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 17 目前的一个已知问题: https://github.com/t4t5/sweetalert/issues/950
作者知道并表示他会尽快推送更新。
请随时投票/观看问题以获取有关此更新的信息。
,我一直在尝试调试事件处理程序未为包装在 swal
内但无法调用的组件调用的原因。因此,根据我有限的理解,React Synthetic Events 不会为此类组件触发,但如果您使用 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>
);
}
这是代码和框链接 - https://codesandbox.io/s/mystifying-jang-jrgex?file=/src/App.js
仍然想知道为什么 React 方式不起作用。没有真正使用过 swal
,所以不知道它的用途。
这是因为 SyntheticEvent 对象是池化的。这意味着 SyntheticEvent 对象将被重用,并且在调用事件处理程序后所有属性都将被取消。
现在你正在重用事件对象,首先是console.log函数,然后是setState。
见https://reactjs.org/docs/legacy-event-pooling.html
,你也可以这样做
onChange={e => setAmount(e.target.value)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。