当前位置:首页 > React

react实现搜索的select

2026-01-27 15:43:49React

React 实现搜索 Select 组件

使用原生 select 实现基础搜索

import React, { useState } from 'react';

function SearchSelect({ options }) {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedOption, setSelectedOption] = useState('');

  const filteredOptions = options.filter(option =>
    option.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div>
      <input
        type="text"
        placeholder="Search..."
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      <select
        value={selectedOption}
        onChange={(e) => setSelectedOption(e.target.value)}
      >
        <option value="">Select an option</option>
        {filteredOptions.map((option, index) => (
          <option key={index} value={option}>
            {option}
          </option>
        ))}
      </select>
    </div>
  );
}

使用第三方库 react-select

安装 react-select 库:

npm install react-select

实现代码:

react实现搜索的select

import React, { useState } from 'react';
import Select from 'react-select';

function SearchableSelect({ options }) {
  const [selectedOption, setSelectedOption] = useState(null);

  return (
    <Select
      value={selectedOption}
      onChange={setSelectedOption}
      options={options}
      isSearchable
      placeholder="Search..."
    />
  );
}

自定义搜索下拉组件

import React, { useState, useRef, useEffect } from 'react';

function CustomSearchSelect({ options }) {
  const [searchTerm, setSearchTerm] = useState('');
  const [isOpen, setIsOpen] = useState(false);
  const [selectedOption, setSelectedOption] = useState('');
  const dropdownRef = useRef(null);

  const filteredOptions = options.filter(option =>
    option.toLowerCase().includes(searchTerm.toLowerCase())
  );

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setIsOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  return (
    <div ref={dropdownRef} style={{ position: 'relative' }}>
      <input
        type="text"
        placeholder="Search..."
        value={isOpen ? searchTerm : selectedOption}
        onChange={(e) => setSearchTerm(e.target.value)}
        onFocus={() => setIsOpen(true)}
      />
      {isOpen && (
        <ul style={{
          position: 'absolute',
          top: '100%',
          left: 0,
          right: 0,
          zIndex: 1,
          border: '1px solid #ccc',
          maxHeight: '200px',
          overflowY: 'auto',
          backgroundColor: 'white'
        }}>
          {filteredOptions.map((option, index) => (
            <li
              key={index}
              style={{ padding: '8px', cursor: 'pointer' }}
              onClick={() => {
                setSelectedOption(option);
                setIsOpen(false);
              }}
            >
              {option}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

实现异步搜索

import React, { useState, useEffect } from 'react';
import Select from 'react-select';
import axios from 'axios';

function AsyncSearchSelect() {
  const [inputValue, setInputValue] = useState('');
  const [options, setOptions] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    if (inputValue) {
      setIsLoading(true);
      const timer = setTimeout(() => {
        axios.get(`https://api.example.com/search?q=${inputValue}`)
          .then(response => {
            setOptions(response.data.map(item => ({
              value: item.id,
              label: item.name
            })));
            setIsLoading(false);
          });
      }, 500);
      return () => clearTimeout(timer);
    }
  }, [inputValue]);

  return (
    <Select
      options={options}
      onInputChange={setInputValue}
      isLoading={isLoading}
      isSearchable
      placeholder="Search..."
    />
  );
}

多选搜索组件

import React, { useState } from 'react';
import Select from 'react-select';

function MultiSearchSelect() {
  const [selectedOptions, setSelectedOptions] = useState([]);
  const options = [
    { value: 'apple', label: 'Apple' },
    { value: 'banana', label: 'Banana' },
    { value: 'orange', label: 'Orange' }
  ];

  return (
    <Select
      isMulti
      value={selectedOptions}
      onChange={setSelectedOptions}
      options={options}
      isSearchable
      placeholder="Search and select multiple items..."
    />
  );
}

这些实现方式涵盖了从简单到复杂的各种搜索选择需求,可以根据项目需求选择合适的方案。react-select 提供了丰富的功能和定制选项,是大多数情况下的推荐选择。

标签: reactselect
分享给朋友:

相关文章

如何生成react代码

如何生成react代码

使用 Create React App 生成项目 安装 Node.js 后,通过命令行工具运行以下命令创建新项目: npx create-react-app my-app cd my-app npm…

如何react页面

如何react页面

创建 React 页面 使用 create-react-app 快速初始化项目: npx create-react-app my-app cd my-app npm start 基础页面结构 在 s…

react如何通信

react如何通信

React 组件通信方式 React 组件间的通信方式多样,具体选择取决于组件关系和场景需求。以下是常见方法: 父子组件通信 父组件通过 props 向子组件传递数据,子组件通过回调函数通知父组件…

react 如何算精通

react 如何算精通

精通 React 的标准 精通 React 不仅需要掌握基础语法和核心概念,还需具备解决复杂问题、优化性能和架构设计的能力。以下是衡量 React 精通程度的关键维度: 核心概念与机制 组件化开…

如何调试react源码

如何调试react源码

调试React源码的方法 克隆React源码仓库到本地: git clone https://github.com/facebook/react.git cd react 安装依赖并构建开发版本:…

react如何引用jquery

react如何引用jquery

在React项目中引用jQuery可以通过以下方法实现: 安装jQuery依赖 通过npm或yarn安装jQuery包: npm install jquery # 或 yarn add jquer…