reactjs - react typescript : Correct ref type for HTML Select with an OnChange with useRef

标签 reactjs typescript

我之前没有在选择框上使用过 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

最佳答案

问题类型错误可以通过将 HTMLInputElementHTMLSelectElement 交换来解决,因为 onChangeselect 上(不是输入)。

要使用 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/

相关文章:

javascript - 创建 TypeScript 类以使用现有的 Javascript 和 Backbone 对象

android - ionic 2 : Run a background service with cordova

javascript - 如何让网页上的图片自动刷新

javascript - ReactJS 表单渲染问题

reactjs - 如何从React Typescript的整个项目中删除未使用的导入/声明?

css - 删除 Navbar 和 Navbar.Header 之间的 <div class ="container"> React Bootstrap

javascript - 如何在Typescript项目中实现顶层等待?

reactjs - React useReducer 异步数据获取

javascript - 需要触发通过映射函数reactjs编写的元素数组中的单个元素

javascript - Visual Studio 为不同的 pc 转换 TypeScript 的不同输出