不能将useState与打字稿一起使用(找不到名称“ useState”)

时间:2020-03-19 10:12:12

标签: javascript reactjs typescript ecmascript-6 react-hooks

以下代码有什么问题?使用useState时,我得到了打字稿的警告

import * as React, { useState } from 'react'

const useForm = (callback: any | undefined) => {
  const [inputs, setInputs] = useState({}) //error: Cannot find name 'useState'.ts(2304)


  const handleInputChange = event => {
    event.persist()
    setInputs(inputs => ({
      ...inputs,
      [event.target.name]: event.target.value,
    }))
  }

  return {
    handleInputChange,
    inputs,
  }
}

export default useForm

https://codesandbox.io/s/react-typescript-starter-lmub8

3 个答案:

答案 0 :(得分:3)

您的导入语句无效。

您可以这样将所有内容都导入为React

import * as React from 'react';

和来自useState对象的访问React

 const [inputs, setInputs] = React.useState({})

或导入React作为默认名称,仅部分导入其他名称:

import React, { useState } from 'react'

和以前一样使用useState

const [inputs, setInputs] = useState({});

答案 1 :(得分:0)

formHook.tsx

中尝试一下
import React, { useState } from 'react';

,并且在app.tsx

import React, { Component } from 'react'
const { inputs, handleInputChange } = useForm;

答案 2 :(得分:0)

您可以先使用React.useState或将其作为单个导出导入。其次,还应指定事件对象,例如更改事件或表单事件。

import * as React from 'react'
import {useState} from 'react';
const useForm = (callback: () => void) => {
  const [inputs, setInputs] = useState({});


  const handleInputChange = (event:React.ChangeEvent<HTMLInputElement>) => {
    event.persist()
    setInputs(inputs => ({
      ...inputs,
      [event.target.name]: event.target.value,
    }))
  }

  return {
    handleInputChange,
    inputs,
  }
}

export default useForm