我想实现与蚂蚁设计自动完成Algolia搜索。但是当我试图提取SearchInput
组件时,我得到了Cannot read property 'focus' of null
错误(没有提取,也就是说,当我把它放在同一个文件中时,它工作得很好)。以下是工作代码:
import React, { useState } from 'react'
import { AutoComplete, Input } from 'antd'
const SearchAutocomplete = connectAutoComplete(
({ hits, currentRefinement, refine }) => {
...
return (
<AutoComplete
options={options}
onSelect={onSelect}
onSearch={handleSearch}
open={open}
>
<Input
value={currentRefinement}
onChange={e => refine(e.currentTarget.value)}
/>
</AutoComplete>
);
}
);
但是,当我将Input
移到像这样的单独组件时,它不起作用:
import React, { useState } from 'react'
import { AutoComplete } from 'antd'
import SearchInput from './SearchInput'
const SearchAutocomplete = connectAutoComplete(
({ hits, currentRefinement, refine }) => {
...
return (
<AutoComplete
options={options}
onSelect={onSelect}
onSearch={handleSearch}
open={open}
>
<SearchInput value={currentRefinement} onChange={e => refine(e.currentTarget.value)}/>
</AutoComplete>
);
}
);
以及SearchInput
组件本身:
import React from 'react'
import { Input } from 'antd'
const SearchInput = props => {
const { value, onChange} = props;
return (
<Input
value={value}
onChange={onChange}
/>
)
}
下面是指向codesandbox的链接,其中包含提取的组件。如何修复此错误?
发布于 2020-07-13 13:24:05
在SearchInput
中添加React.forwardRef()
解决了这个问题:
const SearchInput = React.forwardRef((props, ref) => {
const { onChange } = props;
return (
<Input.Search
onChange={onChange}
ref={ref}
/>
)
})
https://stackoverflow.com/questions/62872707
复制相似问题