【发布时间】:2020-05-03 17:03:53
【问题描述】:
我正在关注this algolia tutorial,我是 Gatsby 的新手。下面的代码目前似乎引起了问题。
我已从 search/index.js 文件中添加了其余代码...
import React, { useState, useEffect, createRef } from "react"
import { InstantSearch, Index, Hits, connectStateResults } from "react-instantsearch-dom"
import algoliasearch from "algoliasearch/lite"
import { Root, HitsWrapper, PoweredBy } from "./styles"
import Input from "./input"
import * as hitComps from "./hitComps"
const Results = connectStateResults(
({ searchState: state, searchResults: res, children }) =>
res && res.nbHits > 0 ? children : `No results for '${state.query}'`
)
const Stats = connectStateResults(
({ searchResults: res }) =>
res && res.nbHits > 0 && `${res.nbHits} result${res.nbHits > 1 ? `s` : ``}`
)
const useClickOutside = (ref, handler, events) => {
if (!events) events = [`mousedown`, `touchstart`]
const detectClickOutside = event =>
!ref.current.contains(event.target) && handler()
useEffect(() => {
for (const event of events)
document.addEventListener(event, detectClickOutside)
return () => {
for (const event of events)
document.removeEventListener(event, detectClickOutside)
}
})
}
export default function Search({ indices, collapse, hitsAsGrid }) {
const ref = createRef()
const [query, setQuery] = useState(``)
const [focus, setFocus] = useState(false)
const searchClient = algoliasearch(
process.env.GATSBY_ALGOLIA_APP_ID,
process.env.GATSBY_ALGOLIA_SEARCH_KEY
)
useClickOutside(ref, () => setFocus(false))
return (
<InstantSearch
searchClient={searchClient}
indexName={indices[0].name}
onSearchStateChange={({ query }) => setQuery(query)}
root={{ Root, props: { ref } }}
>
<Input onFocus={() => setFocus(true)} {...{ collapse, focus }} />
<HitsWrapper show={query.length > 0 && focus} asGrid={hitsAsGrid}>
{indices.map(({ name, title, hitComp }) => (
<Index key={name} indexName={name}>
<header>
<h3>{title}</h3>
<Stats />
</header>
<Results>
<Hits hitComponent={hitComps[hitComp](() => setFocus(false))} />
</Results>
</Index>
))}
<PoweredBy />
</HitsWrapper>
</InstantSearch>
)
}
页面加载,然后点击屏幕上的任意位置会出现以下错误...
TypeError: Cannot read property 'contains' of null
HTMLDocument.detectClickOutside
src/components/search/index.js:21
18 |
19 | const useClickOutside = (ref, handler, events) => {
20 | if (!events) events = [`mousedown`, `touchstart`]
21 | const detectClickOutside = event =>
22 | !ref.current.contains(event.target) && handler()
23 | useEffect(() => {
24 | for (const event of events)
我确定这是一个非常基本的错误。如果有人有任何提示,我将不胜感激。谢谢。
【问题讨论】:
-
请分享使用此钩子的组件,可能是您在组件中定义引用时出现的问题。
-
谢谢。我已从该文件 (search/index.js) 中添加了其余代码
-
最新版本的 React InstantSearch 上不存在
root属性。您使用常规元素将侦听器挂钩。 github.com/algolia/react-instantsearch/blob/master/… -
@samuel-vaillant 您的建议是正确的,这会导致其他已更新插件出现更多问题。非常感谢,我会继续努力的。