1 回答

TA貢獻1815條經(jīng)驗 獲得超6個贊
你的代碼寫錯了。connectSearchBox旨在將組件連接到 Algolia api。這是對組件定義的一次性設(shè)置。它返回一個高階組件,該組件使用 api 功能包裝給定組件。您可以在此處查看源代碼。通過將您的自定義 SearchBox 放在 SearchBox 函數(shù)中,您會導致組件在每個 render() 循環(huán)中重新構(gòu)建和重新連接,從而不會保留狀態(tài)。這就是為什么一旦您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}
/>
文檔中的用法示例。我認為您想要實現(xiàn)的是將 props 傳遞給您的組件,但connectSearchBox已經(jīng)保證您傳遞給 HOC 的任何 props 也會傳遞到您的自定義搜索框。
添加回答
舉報