📜  如何在 ReactJS 中为自动完成添加样式?

📅  最后修改于: 2022-05-13 01:56:26.130000             🧑  作者: Mango

如何在 ReactJS 中为自动完成添加样式?

自动完成组件用于使用选项值自动完成文本值。它基本上允许用户从建议列表中键入和选择项目。它通过在用户键入时提供建议来改善用户体验。

在本文中,您将研究如何在 ReactJS 中设置自动完成组件的样式。

创建 React 应用程序并安装模块:

  • 第 1 步:使用以下命令创建一个 React 应用程序:

    npx create-react-app foldername

  • 第 2 步:创建项目文件夹(即文件夹名称)后,使用以下命令移动到该文件夹:

    cd foldername
  • 第 3 步:创建 ReactJS 应用程序后,使用以下命令安装所需的模块:

    npm install --save react-autocomplete

项目结构:它将如下所示。

项目结构

示例:现在在 App.js 文件中写下以下代码。在这里,App 是我们编写代码的默认组件。以下代码添加了带有样式的自动完成组件。

App.js
import React, { useState } from 'react'
import Autocomplete from 'react-autocomplete'
  
function App() {
  
    // Defining a state named value, which
    // we can update by calling setValue 
    // Value will store the typed value or
    // selected suggestion by the user
    const [value, setValue] = useState('');
  
    return (
        
            
                {/* Inline css*/}                 

                    Geeks for Geeks : React                      Autocomplete Component Styling                 

            
            
                 item.label.toLowerCase()                         .indexOf(value.toLowerCase()) > -1}                     getItemValue={item => item.label}                     renderItem={(item, isHighlighted) =>                         // Styling to highlight selected item                         
                            {item.label}                         
                    }                     value={value}                        // The onChange event watches for                     // changes in an input field                     onChange={e => setValue(e.target.value)}                        // To set the state variable to value                     // selected from dropdown                     onSelect={(val) => setValue(val)}                        // Added style in Autocomplete component                     inputProps={{                         style: {                             width: '300px', height: '20px',                             background: '#e4f3f7',                              border: '2px outset lightgray'                         },                         placeholder: 'Search language'                     }}                 />             
        
    ); }    export default App;


解释:

  • 在 Autocomplete 元素上,className 并不适用于您可能期望的文本输入。您不能在自动完成组件上使用 className,您必须使用 inputProps 属性。
  • inputProps 通常用于(但不限于)占位符、事件处理程序(onFocus、onBlur 等)、autoFocus 等。
  • 您可以在上面的代码中自定义 inputProps 中的样式。
  • 在 renderItem 属性中,您可以将样式添加为一组样式,这些样式可用于改善下拉菜单中项目的外观。

运行应用程序的步骤:从项目的根目录使用以下命令运行应用程序:

npm start

输出:现在打开浏览器并转到http://localhost:3000/ ,您将看到以下输出:

选择语言自动完成

参考: https://www.npmjs.com/package/react-autocomplete