TypeScript React: Get form values with useRef
我想将表单中的任何值发布到API,即时通讯使用useRef来获取这样的表单...
1 | const formElement = useRef<HTMLFormElement>(null); |
提交功能
1 2 3 4 5 | const submit = async (event: React.FormEvent) => { event.preventDefault(); const body = new URLSearchParams(new FormData(formElement.current)); // <=== error const response = await fetch(baseUrl, { body, method: 'post'}); }; |
和表格
1 2 3 | <form onSubmit={submit} ref={formElement}> <input type='text' id='test' value='testValue'/> </form> |
我得到的错误是在控制台中,然后它无法编译
Type 'null' is not assignable to type 'HTMLFormElement | undefined'.ts(2345)
整个组件在这里...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | <Poster method='post' baseUrl='https://api.funge.it/join' auth={false} keys='email, fullName, password, username' /> import React, { useContext, useRef, useState } from 'react'; import { BEARER_TOKEN, Dispatch, Global } from '../globalState'; interface PropsInterface { auth: boolean; baseUrl: string; keys: string; method: string; } const Poster: React.FC<PropsInterface> = (props: PropsInterface) => { const { global } = useContext(Global); const { dispatch } = useContext(Dispatch); const [state, setState] = useState({ auth: props.auth, baseUrl: props.baseUrl, keys: props.keys.split(','), method: props.method, }); const { auth, baseUrl, keys, method } = state; const { bearer } = global; const baseUrlRef = useRef<HTMLInputElement>(null); // const formElement = useRef<HTMLFormElement>(null); // const formElement = useRef<HTMLFormElement | null>(); // const formElement = useRef<HTMLFormElement | undefined>(); const formElement = React.useRef() as React.MutableRefObject<HTMLFormElement>; const submit = async (event: React.FormEvent) => { event.preventDefault(); setState((prev) => ({ ...prev, loading: true })); const body = new URLSearchParams(new FormData(formElement.current)); const response = await fetch(baseUrl, { body, method }); const content = await response.json(); setState((prev) => ({ ...prev, response, loading: false })); if (response.status === 200 && content.jwtToken) { dispatch({ type: BEARER_TOKEN, value: content.jwtToken }); } }; const copy = (event: React.MouseEvent) => { event.preventDefault(); if (baseUrlRef.current) baseUrlRef.current.select(); document.execCommand('copy'); const button = event.target as HTMLButtonElement; button.focus(); }; return ( <form className='poster' onSubmit={submit} ref={formElement}> {method} <input type='text' value={baseUrl} ref={baseUrlRef} readOnly className='poster--url' /> <button className='poster--send'>Send</button> <button className='poster--copy' onClick={copy}> Copy </button> {auth && ( Bearer Token <input type='text' value={bearer} readOnly className='poster--url' /> )} {keys.map((item, index) => { return ( {item}: <input type='text' id={item} key={index} className='poster--value-title' /> ); })} </form> ); }; export { Poster }; |
UPDATE Natarich J我现在在输入的ref中得到此错误
1 2 3 4 5 6 7 | I so wish it did but i now get an error in the ref part of the input `Type 'MutableRefObject<HTMLFormElement | undefined>' is not assignable to type 'string | ((instance: HTMLFormElement | null) => void) | RefObject<HTMLFormElement> | null | undefined'. Type 'MutableRefObject<HTMLFormElement | undefined>' is not assignable to type 'RefObject<HTMLFormElement>'. Types of property 'current' are incompatible. Type 'HTMLFormElement | undefined' is not assignable to type 'HTMLFormElement | null'. Type 'undefined' is not assignable to type 'HTMLFormElement | null'.ts(2322) index.d.ts(106, 9): The expected type comes from property 'ref' which is declared here on type 'DetailedHTMLProps<FormHTMLAttributes<HTMLFormElement>, HTMLFormElement>'` |
错误日志基本上表明存在类型不匹配。可能是因为您将
因为
1 2 | typeof formElement ===> <HTMLFormElement> || null typeof data_that_FormData_receives ===> <HTMLFormElement> || undefined |
您看到不匹配。所以可能的解决方案是
1 2 3 | # I forgot whether should be '|' or '||', play around with it... const formElement = useRef<HTMLFormElement || undefined>(); |
告诉我是否可行
更新:
此外,您不需要
1 | const body = new FormData(formElement.current) |