Programing

typecript와 함께 State를 사용할 수 없음('useState' 이름을 찾을 수 없음)

c10106 2022. 4. 1. 19:53
반응형

typecript와 함께 State를 사용할 수 없음('useState' 이름을 찾을 수 없음)

아래 코드에 문제가 있는 것은?useState를 사용할 때 typecript를 통해 경고를 받은 경우

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

수입 명세서가 유효하지 않다.

다음 이름으로 모든 것을 가져올 수 있다.React다음과 같은 경우:

import * as React from 'react';

그리고 접근권useState처음부터React객체:

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

또는 수입하다React기본값으로 사용되며 일부만 다른 이름 가져오기:

import React, { useState } from 'react'

그리고 사용useState이전과 같이:

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

이것을 사용해 보십시오.formHook.tsx

import React, { useState } from 'react';

그리고 이것.app.tsx

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

너는 먼저 사용할 수 있다.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

참조URL: https://stackoverflow.com/questions/60754963/cant-use-usestate-with-typescript-cannot-find-name-usestate

반응형