React-TypeScript应用:实现输入3个字符后显示自动联想下拉结果求助
Solution for Showing Dropdown Results Only After 3+ Characters
Hey Olivia, let's fix this for both the react-search-box and react-autosuggest packages you're using—each has a straightforward approach tailored to their APIs.
1. For react-search-box
This package doesn’t have a built-in prop to control when suggestions appear, so we’ll handle it by filtering the data we pass to the component based on input length.
Step-by-Step Modifications:
- Add an
inputValuestate to track the user’s typed text. - Update your
handleChangefunction to sync this state with the input. - Only pass filtered data to the
<Search>component when the input has 3+ characters; otherwise, pass an empty array (so no results show).
Updated Code:
export class myApp extends React.Component<any, any> { constructor() { super(); this.state = { data: [], loading: false, inputValue: '' // Track user input here }; this.handleChange = this.handleChange.bind(this); } componentDidMount(){ this.setState({ loading: true}); fetch('serviceUrl......') .then(res => res.json()) .then(data => { this.setState({ data: data.items, loading: false }); }) } handleChange(inputValue: string) { this.setState({ inputValue }); } render(){ // Filter data only if input meets the 3-character threshold const filteredData = this.state.inputValue.length >= 3 ? this.state.data.filter(item => item.fName.toLowerCase().includes(this.state.inputValue.toLowerCase()) ) : []; return ( <div className="div_search"> <Search data={filteredData} onChange={this.handleChange} placeholder="Enter the name..." className="search_box" // Note: React uses `className` instead of `class` searchKey="fName" /> </div> ) } }
2. For react-autosuggest
This package has a dedicated shouldRenderSuggestions prop that makes controlling dropdown visibility much simpler.
Step-by-Step Modifications:
- Add
inputValueandsuggestionsto your state. - Create a helper function to filter suggestions based on user input.
- Use
shouldRenderSuggestionsto only show the dropdown when the input has 3+ characters.
Updated Code:
import Autosuggest from 'react-autosuggest'; // Helper to filter matching suggestions const getSuggestions = (data: any[], inputValue: string) => { const lowercaseInput = inputValue.toLowerCase(); return data.filter(item => item.fName.toLowerCase().includes(lowercaseInput) ); }; // Customize how each suggestion is displayed const renderSuggestion = (suggestion: any) => ( <div>{suggestion.fName}</div> ); export class myApp extends React.Component<any, any> { constructor() { super(); this.state = { data: [], loading: false, inputValue: '', suggestions: [] }; this.handleChange = this.handleChange.bind(this); this.onSuggestionsFetchRequested = this.onSuggestionsFetchRequested.bind(this); } componentDidMount(){ this.setState({ loading: true}); fetch('serviceUrl......') .then(res => res.json()) .then(data => { this.setState({ data: data.items, loading: false }); }) } handleChange(event: React.ChangeEvent<HTMLInputElement>, { newValue }: { newValue: string }) { this.setState({ inputValue: newValue }); } onSuggestionsFetchRequested({ value }: { value: string }) { // Only fetch suggestions if input is 3+ characters long if (value.length >= 3) { this.setState({ suggestions: getSuggestions(this.state.data, value) }); } else { this.setState({ suggestions: [] }); } } render(){ const { inputValue, suggestions } = this.state; const inputProps = { placeholder: "Enter the name...", value: inputValue, onChange: this.handleChange, className: "search_box" }; return ( <div className="div_search"> <Autosuggest suggestions={suggestions} onSuggestionsFetchRequested={this.onSuggestionsFetchRequested} onSuggestionsClearRequested={() => this.setState({ suggestions: [] })} shouldRenderSuggestions={() => inputValue.length >= 3} // Controls dropdown visibility getSuggestionValue={(suggestion) => suggestion.fName} renderSuggestion={renderSuggestion} inputProps={inputProps} /> </div> ) } }
Key Notes:
- The
shouldRenderSuggestionsprop ensures the dropdown never appears until the user types 3+ characters. - We clear suggestions when the input is too short to avoid leftover results from previous valid inputs.
内容的提问来源于stack exchange,提问作者Olivia
相关产品推荐
相关产品推荐

