1 回答

TA贡献1815条经验 获得超6个赞
你的代码写错了。connectSearchBox旨在将组件连接到 Algolia api。这是对组件定义的一次性设置。它返回一个高阶组件,该组件使用 api 功能包装给定组件。您可以在此处查看源代码。通过将您的自定义 SearchBox 放在 SearchBox 函数中,您会导致组件在每个 render() 循环中重新构建和重新连接,从而不会保留状态。这就是为什么一旦您setState的搜索文本消失。
import { connectSearchBox } from 'react-instantsearch-dom';
const CustomSearchBox = ({ currentRefinement, refine, openDisplay, closeDisplay, ...props }) => {
const handleChange = (e, refine) => {
refine(e.target.value)
if (e.target.value !== "")
openDisplay();
else
closeDisplay();
}
return (
<label>
<ul style={styles.container}>
<input
style={styles.input}
type="text"
value={currentRefinement}
onChange={e => handleChange(e, refine)}
/>
</ul>
</label>
)
})
export default connectSearchBox(CustomSearchBox);
用法
import CustomSearchBox from './CustomSearchBox'
...
<CustomSearchBox
openDisplay={this.openDisplay}
closeDisplay={this.closeDisplay}
/>
文档中的用法示例。我认为您想要实现的是将 props 传递给您的组件,但connectSearchBox已经保证您传递给 HOC 的任何 props 也会传递到您的自定义搜索框。
添加回答
举报