React JS 中的搜索栏!

2025-06-04

React JS 中的搜索栏!

嗨,大家好!

在本文中,我们将学习如何在 React JS 中创建一个功能齐全的搜索栏。我们将首先设置一些示例内容,然后使用创建的搜索栏实现搜索功能。

在我的博客上阅读这篇文章


创建搜索栏

要创建搜索栏,我们首先要创建一个基本的文本字段。在本教程中,我们将使用 Material UI,这是一个优秀的 React UI 库,提供了各种组件。请按照以下步骤使用 npm 安装 Material UI:

npm install @mui/material
Enter fullscreen mode Exit fullscreen mode

在 app.js 中,从 Material UI 导入文本字段组件。我们将使用文本字段的轮廓变体。

import { React, useState } from "react";
import TextField from "@mui/material/TextField";
import List from "./Components/List"
import "./App.css";

function App() {
  return (
    <div className="main">
      <h1>React Search</h1>
      <div className="search">
        <TextField
          id="outlined-basic"
          variant="outlined"
          fullWidth
          label="Search"
        />
      </div>
      <List />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

你可能会注意到一些事情。我们正在导入一个名为 List.js 的文件,我们现在将创建它。它将包含我们的虚拟数据列表。

接下来,将以下 CSS 添加到您的 App.css:

.main {
    display: flex;
    height: 100vh;
    width: 100%;
    align-items: center;
    flex-direction: column;
    row-gap: 20px;
}

h1 {
    margin: 10px;
    font-size: 40px;
    color: rgb(1, 1, 59);
}

.search {
    width: 30%;
}

ul li {
    font-size: 20px;
} 
Enter fullscreen mode Exit fullscreen mode

创建虚拟内容

在src文件夹中创建一个名为Components的新文件夹。在其中创建两个文件,一个名为ListData.JSON的 JSON 文件和List.JS文件。

对于示例文本或内容,我使用了Mockaroo。您可以从这里获取各种真实的测试数据。对于此示例,您也可以使用我的 ListData.JSON:

[{
    "id": 1,
    "text": "Devpulse"
}, {
    "id": 2,
    "text": "Linklinks"
}, {
    "id": 3,
    "text": "Centizu"
}, {
    "id": 4,
    "text": "Dynabox"
}, {
    "id": 5,
    "text": "Avaveo"
}, {
    "id": 6,
    "text": "Demivee"
}, {
    "id": 7,
    "text": "Jayo"
}, {
    "id": 8,
    "text": "Blognation"
}, {
    "id": 9,
    "text": "Podcat"
}, {
    "id": 10,
    "text": "Layo"
}] 
Enter fullscreen mode Exit fullscreen mode

创建列表

现在我们将这些数据映射到 List 中。在 List.JS 文件中,添加以下代码:

import { React, useState } from 'react'
import data from "./ListData.json"

function List(props) {
    return (
        <ul>
            {data.map((item) => (
                <li key={item.id}>{item.text}</li>
            ))}
        </ul>
    )
}

export default List
Enter fullscreen mode Exit fullscreen mode

您的页面现在看起来应该是这样的:

浏览器视图

获取用户输入

现在我们需要将用户输入存储在一个状态中。我们将使用文本字段上的 onChange 事件处理程序和一个在用户每次输入时更新状态的函数来实现。

注意:创建搜索栏时,始终将输入文本转换为小写。

我们还将状态以 props 的形式传递给 List 组件。
你的 App.js 现在看起来如下:

import { React, useState } from "react";
import TextField from "@mui/material/TextField";
import List from "./Components/List";
import "./App.css";

function App() {
  const [inputText, setInputText] = useState("");
  let inputHandler = (e) => {
    //convert input text to lower case
    var lowerCase = e.target.value.toLowerCase();
    setInputText(lowerCase);
  };

  return (
    <div className="main">
      <h1>React Search</h1>
      <div className="search">
        <TextField
          id="outlined-basic"
          onChange={inputHandler}
          variant="outlined"
          fullWidth
          label="Search"
        />
      </div>
      <List input={inputText} />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

过滤数据

现在,我们将使用 filter 函数过滤数据,并创建一个名为 filteredData 的新数组。我们将用这个数组代替原始数组。
我们还将列表数据转换为小写,以匹配用户输入。用户输入可以通过 props 访问。
这将是你的 List.js:

import { React, useState } from 'react'
import data from "./ListData.json"

function List(props) {
    //create a new array by filtering the original array
    const filteredData = data.filter((el) => {
        //if no input the return the original
        if (props.input === '') {
            return el;
        }
        //return the item which contains the user input
        else {
            return el.text.toLowerCase().includes(props.input)
        }
    })
    return (
        <ul>
            {filteredData.map((item) => (
                <li key={item.id}>{item.text}</li>
            ))}
        </ul>
    )
}

export default List
Enter fullscreen mode Exit fullscreen mode

结果

您的功能搜索栏将如下所示:
结果

您已完成!

代码也在我的 GitHub 上。
链接


感谢大家阅读这篇文章!也
欢迎访问我的博客

文章来源:https://dev.to/salehmubahar/search-bar-in-react-js-545l
PREV
Why (I think) "Cost of Living" pay for remote workers is BS. 1. The Fundamental Message Is Terrible. 2. The "Quality of Life" Argument is also BS. 3. It's Legally Dangerous. 4. It's Game-able 5. It Goes Against The Essence of Remote Working, In The Most Greedy Way. 6. "It shouldn't just be about the money!" 7. It can punish people who are already disadvantaged. 8. These pay differences compound.
NEXT
专业人士如何摆脱相对导入 输入 jsconfig.json 基本 URL 路径 TypeScript 总结 感谢阅读