我尝试将表单值传递给useRef钩子,但返回的是表单HTML tag
我尝试推断chevrons中的HTMLFormElement
类型,并将null作为useRef钩子的当前值。
下面是该文件的其余部分:NameTodo.tsx
import React, { FC, ChangeEvent, FormEvent, useState, useRef } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { addTodoName, toggleNaming } from '../todoReducer';
import { RootState } from '../todoStore';
const NameTodo: FC = () => {
const dispatch = useDispatch();
const selector = useSelector((state: RootState) => { return state.todo })
const [input, setInput] = useState<any>('');
// Current value returns the HTML form tag itself instead of its value
const ref = useRef<HTMLFormElement>(null);
const exitNamingMenu = (): void => {
dispatch(toggleNaming(false));
}
const handleInput = (event: ChangeEvent<HTMLInputElement>): void => {
event.preventDefault();
setInput(event.target.value);
}
const submitTodoName = (event: FormEvent<HTMLFormElement>): void => {
event.preventDefault();
//dispatch(addTodoName(input));
console.log(ref.current);
dispatch(toggleNaming(false));
}
return (
<div className='position-absolute start-50 mt-4 translate-middle bg-success' style={{ width: '18vw', height: '20vh' }}>
<span className='position-absolute end-0'>
<button className='text-white bg-success bg-opacity-10 border border-0' onClick={exitNamingMenu}>x</button>
</span>
<form className='d-flex flex-column' ref={ref} onSubmit={submitTodoName}>
<p className='text-white text-center' style={{ marginTop: '3vh' }}>Enter the name of your todo-list</p>
<input type='text' name="input" className='p-1 rounded bg-light border-0 ms-4' style={{ width: '15vw' }} onChange={handleInput}></input>
<button type="submit" className='btn btn-light mt-3' style={{ width: "6vw", marginLeft: '6vw' }}>Enter</button>
</form>
</div>
)
}
export default NameTodo
没有错误显示,所以除了这个,其他一切都很好...
提前感谢您的回复:)
1条答案
按热度按时间ee7vknir1#
你可以在input元素上使用ref来获取值,form没有value,对于复杂的表单,你可以使用Formik和React Hook Form这样的库,它们都很棒。
您可以查看下面链接中的示例:
https://codesandbox.io/s/react-template-forked-loq0yn?file=/src/index.js
如果你想和州政府交涉: