我想在keydownListener这个方法中去取上面定义好的最新的value的值,但是发现每次取到的都是初始的值。哪位大神一页到过这中问题,烦请解答一下,不胜感激。functionInput(props){letinputRef=useRef(null);let{value,handleChange,handleKeyDown,handleBlur,handleFocus}=useInputValue(inputRef,props.addTodo);return()exportconstuseInputValue=(inputRef,addTodo)=>{let[value,setValue]=useState('');letfocusStatus=useRef(false);consthandleChange=useCallback((e)=>{letv=e.target.value;setValue(v);},[])consthandleFocus=()=>{focusStatus.current=true;inputRef.current.addEventListener('keydown',keydownListener);}consthandleBlur=()=>{focusStatus.current=false;inputRef.current.removeEventListener('keydown',keydownListener);}constkeydownListener=(e)=>{if(e.keyCode===13&&focusStatus.current){addTodo(value);//????这个地方取到的值始终都是''setValue('');}}return{value,handleChange,handleBlur,handleFocus}
2 回答
潇湘沐
TA贡献1816条经验 获得超6个赞
functionuseClosure(fn){constfnRef=useRef();constfnProxy=useCallback(()=>fnRef.current(),[]);useEffect(()=>{fnRef.current=fn;});returnfnProxy;}constuseInputValue=(inputRef,addTodo)=>{let[value,setValue]=useState('');//...constkeydownListener=useClosure((e)=>{if(e.keyCode===13&&focusStatus.current){addTodo(value);//总会取到当前的valuesetValue('');}});//...};
添加回答
举报
0/150
提交
取消