我之前没有在选择框上使用过 useRef 钩子(Hook), typescript 似乎在提示我的 ref 类型错误?
import React, {useState, useRef} from 'react';
const App: React.FC = () => {
const [state, setState] = useState({country: ''});
const formValue = (event: React.ChangeEvent<HTMLInputElement>) => {setState({...state, [event.target.name]: event.target.value.trim()})}
const country = useRef<HTMLSelectElement>(null);
return (
<div className="layout-grid">
<div className='layout-title'>Identity</div>
<div className='section-grid'>
<div>Country Information</div>
<div>
<label>Country</label>
<select ref='country' onChange={formValue} name="country" value={state.country} >
<option value="First Choice">First Choice</option>
<option value="Second Choice">Second Choice</option>
<option value="Third Choice">Third Choice</option>
<option value="Fourth Choice">Fourth Choice</option>
</select>
</div>
</div>
我得到的错误是
Type '(event: ChangeEvent<HTMLInputElement>) => void' is not assignable to type '(event: ChangeEvent<HTMLSelectElement>) => void'.
Types of parameters 'event' and 'event' are incompatible.
Type 'ChangeEvent<HTMLSelectElement>' is not assignable to type 'ChangeEvent<HTMLInputElement>'.
Type 'HTMLSelectElement' is missing the following properties from type 'HTMLInputElement': accept, align, alt, checked, and 33 more.ts(2322)
index.d.ts(2117, 9): The expected type comes from property 'onChange' which is declared here on type 'DetailedHTMLProps<SelectHTMLAttributes<HTMLSelectElement>, HTMLSelectEle
最佳答案
问题类型错误可以通过将 HTMLInputElement
与 HTMLSelectElement
交换来解决,因为 onChange
在 select
上(不是输入
)。
要使用 ref,必须传递使用 useRef
(country
) 创建的 ref 变量(不是字符串 "country"
)。
const App: React.FC = () => {
const [state, setState] = React.useState({ country: "" });
const formValue = (event: React.ChangeEvent<HTMLSelectElement>) => {
setState({ ...state, [event.target.name]: event.target.value.trim() });
};
const country = React.useRef<HTMLSelectElement>(null);
// On first render, this will be null. Subsequent renders with log the value.
console.log(country.current && country.current.value)
return (
<div className="layout-grid">
<div className="layout-title">Identity</div>
<div className="section-grid">
<div>Country Information</div>
<div>
<label>Country</label>
<select
ref={country}
onChange={formValue}
name="country"
value={state.country}
>
<option value="First Choice">First Choice</option>
<option value="Second Choice">Second Choice</option>
<option value="Third Choice">Third Choice</option>
<option value="Fourth Choice">Fourth Choice</option>
</select>
</div>
</div>
</div>
);
};
编辑:回答您的评论:
如果你想重用 formValue
你可以传递 ChangeEvent
一个联合类型的可能元素。例如:
const formValue = (
event: React.ChangeEvent<HTMLSelectElement | HTMLInputElement>
) => {
setState({ ...state, [event.target.name]: event.target.value.trim() });
};
关于reactjs - react typescript : Correct ref type for HTML Select with an OnChange with useRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57984414/