import React, {
FunctionComponent,
useState,
useEffect
} from 'react'
const SearchBar: FunctionComponent = () => {
const [searchValue, setSearchValue] = useState < string > ('')
const [isSuggestionOpen, setIsSuggestionOpen] = useState < boolean > (false)
async function showSuggestedWords(event) {
setSearchValue(event.target.value)
try {
const res = await fetch(`https://www.someurl.com/q=${searchValue}`)
const suggestedWordsArray = await res.json()
// setSuggestedWords(suggestedWordsArray[1].slice(0, 10))
setIsSuggestionOpen(true)
return
} catch {
console.log('error fetching suggested results')
setIsSuggestionOpen(false)
}
}
return ( <
div >
<
form action = "/Controller"
method = "get" >
<
input name = "q"
type = "text"
value = {
searchValue
}
onChange = {
showSuggestedWords
}
autoComplete = "off"
autoCapitalize = "off"
autoCorrect = "off"
spellCheck = "false"
placeholder = "Search here" /
>
<
button type = "submit" >
Submit <
/button> <
/form> <
/div>
)
}
ReactDOM.render( <
div > < h1 > Hello, world! < /h1> <SearchBar / > < /div>,
document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/typescript/4.0.3/typescript.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
我是Typescript的新手,所以它可能是一个明显的解决方案。
我有一个由React,Nextjs和Typescript组成的项目。
我使用打字稿来定义我的状态类型,如下所示:
const [searchValue, setSearchValue] = useState<string>('')
在运行时出现错误:
ReferenceError: string is not defined
。
我不知道怎么了。我检查的所有地方都建议像上面一样定义状态类型。
这是我的打字稿配置:
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"noImplicitAny": true,
"allowSyntheticDefaultImports": true
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx"
],
"exclude": [
"node_modules"
]
}
我没有webpack配置,因为它们与Nextjs一起提供(已配置为可与打字稿一起使用)。
我确实安装了@types/react @types/react-dom @types/node
。
有任何提示吗?
答案 0 :(得分:0)
原来是我的babel.config.json
中的配置不匹配
我删除了所有内容,只保留了这些行:
{
"presets": ["next/babel"],
"env": {
"test": {
"presets": ["next/babel"]
}
}
}
这样,我仍然可以运行我的Jest测试。
希望在这种情况下对其他人有帮助:)