建设网站硬件厦门市建设局查询保障摇号网站首页
在这个问题中,用户希望在点击确认按钮时触发handleChange函数,并且能够正确获取到最新的bzText值。最初的代码中,在handleOpen函数中弹出一个确认框,并在确认框的onOk回调函数中调用handleChange函数。然而,由于组件传值问题,导致在onOk回调函数中无法获取到最新的bzText值。
const handleOpen = () => {Modal.confirm({title: `是否申请解锁经办人姓名`,content: (<div className={styles.bz}>备注:<InputonChange={(e) => {setBzText(e?.target?.value);}}placeholder="请输入"/></div>),cancelText: '取消',okText: '确认',onOk() {handleChange('change', bzText);}});
};const handleChange = (type, bzText) => {console.log(bzText, 'bzText');
};// bzText是用useState声明的
为了解决这个问题,可以使用useRef来创建一个引用(bzTextRef),并在输入框的onChange事件中更新这个引用的值。然后,在确认框的onOk回调函数中通过bzTextRef.current来获取最新的bzText值,从而确保在handleChange函数内部能够正确访问到最新的值。
import { useRef } from 'react';const YourComponent = () => {const bzTextRef = useRef(null);const handleOpen = () => {Modal.confirm({title: `是否申请解锁经办人姓名`,content: (<div className={styles.bz}>备注:<InputonChange={(e) => {bzTextRef.current = e?.target?.value;}}placeholder="请输入"/></div>),cancelText: '取消',okText: '确认',onOk() {handleChange('change', bzTextRef.current);}});};const handleChange = (type, bzText) => {console.log(bzText, 'bzText');};// bzText是用useState声明的
};export default YourComponent;
综上所述,通过使用useRef来存储bzText的引用,可以解决在确认框中无法获取到最新值的问题。
