以下代码有什么问题?使用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
答案 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