最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - can't use useState with typescript (Cannot find name 'useState') - Stack Overflow

programmeradmin5浏览0评论

What is the problem with below code? I got warning by typescript when use 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

What is the problem with below code? I got warning by typescript when use 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

Share Improve this question edited Sep 27, 2020 at 10:18 falinsky 7,4284 gold badges34 silver badges58 bronze badges asked Mar 19, 2020 at 10:12 JenniferJennifer 3432 gold badges3 silver badges12 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 12

Your import statement is invalid.

You can either import everything as React like this:

import * as React from 'react';

and the access useState from the React object:

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

or import React as the default and only partially import other names:

import React, { useState } from 'react'

And the use useState as before:

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

Try this in formHook.tsx

import React, { useState } from 'react';

and this in app.tsx

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

you can first use React.useState or import it as individual export. second, you should also specify the event object such as change event or form event.

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
发布评论

评论列表(0)

  1. 暂无评论