下面的代码有什么问题?我在使用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
您的导入语句无效。
您可以将所有内容导入为React
,如下所示:
import * as React from 'react';
以及来自CCD_ 3对象的访问CCD_
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
或将其作为单独导出导入。其次,您还应该指定事件对象,例如change事件或form事件。
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