自动完成是一种输入字段根据用户输入建议单词的功能。这有助于改善应用程序中的用户体验,例如需要搜索的情况。
在本文中,您将研究如何在 React 中构建自动完成组件。您将使用固定的建议列表、事件绑定、理解键盘代码以及操作状态管理。
要完成本教程,您将需要以下内容:
- 需要了解 React。要了解有关 React 的更多信息,请查看如何在 React 中编码 series.
The Autocomplete
组件是您在自动完成功能中制作功能的地方。
创建一个Autocomplete.js
文件,然后导入 React 并实例化Autocomplete
class:
自动完成.js
import React, { Component, Fragment } from "react";
import './styles.css'
class Autocomplete extends Component {
constructor(props) {
super(props);
this.state = {
activeSuggestion: 0,
filteredSuggestions: [],
showSuggestions: false,
userInput: ""
};
}
在您所在的州,activeSuggestion
属性定义所选建议的索引。该物业filteredSuggestions
,设置为空数组,匹配用户的输入。这showSuggestions
属性将决定是否出现建议列表,并且userInput
属性为自己分配一个空字符串,用于接受用户输入的单词。
启动类并设置状态后,让我们看看要在组件中应用的方法。
In your Autocomplete.js
文件,定义一个onChange
方法并更新你的状态:
自动完成.js
onChange = e => {
const { suggestions } = this.props;
const userInput = e.currentTarget.value;
const filteredSuggestions = suggestions.filter(
suggestion =>
suggestion.toLowerCase().indexOf(userInput.toLowerCase()) > -1
);
this.setState({
activeSuggestion: 0,
filteredSuggestions,
showSuggestions: true,
userInput: e.currentTarget.value
});
};
方法onChange
当用户更改输入值时会触发。每次更改时,该方法都会过滤到建议列表并返回不包含用户输入的建议。一旦过滤器通过,.setState()
方法将修改您所在州的userInput
属性包含一个值,设置你的showSuggestions
布尔值以允许显示建议,并重置activeSuggestion
每个方法调用的属性。
The onClick
当用户单击建议时,事件将被调用。在你的Autocomplete.js
文件,声明一个onClick
方法并实现.setState()
method:
自动完成.js
onClick = e => {
this.setState({
activeSuggestion: 0,
filteredSuggestions: [],
showSuggestions: false,
userInput: e.currentTarget.innerText
});
};
The .setState()
方法将更新用户的输入并重置您的状态属性。
The onKeyDown
当用户按下某个键时,方法将启动。在你的Autocomplete.js
文件,声明一个onKeyDown
方法并设置几个条件:
自动完成.js
onKeyDown = e => {
const { activeSuggestion, filteredSuggestions } = this.state;
if (e.keyCode === 13) {
this.setState({
activeSuggestion: 0,
showSuggestions: false,
userInput: filteredSuggestions[activeSuggestion]
});
} else if (e.keyCode === 38) {
if (activeSuggestion === 0) {
return;
}
this.setState({ activeSuggestion: activeSuggestion - 1 });
}
// User pressed the down arrow, increment the index
else if (e.keyCode === 40) {
if (activeSuggestion - 1 === filteredSuggestions.length) {
return;
}
this.setState({ activeSuggestion: activeSuggestion + 1 });
}
};
一旦你存储了你的财产activeSuggestion
and filteredSuggestion
在解构对象中,条件将检查用户按下的键是否与键代码匹配。第一个条件将检查密钥代码是否匹配13
、回车键,然后运行.setState()
方法来更新userInput
属性并关闭建议列表。如果用户按下向上箭头,则键代码38
,条件将减少索引activeSuggestion
属性,如果索引为零则不返回任何内容。如果用户按下向下箭头,则键代码40
,条件将增加索引activeSuggestion
属性,如果索引与长度匹配则不返回任何内容filteredSuggestions
财产。
现在您的方法已经完成,让我们开始应用您的方法render
生命周期方法。
In your Autocomplete.js
文件,设置一个render()
语句,并在解构对象中定义您的方法和状态:
自动完成.js
render() {
const {
onChange,
onClick,
onKeyDown,
state: {
activeSuggestion,
filteredSuggestions,
showSuggestions,
userInput
}
} = this;
let suggestionsListComponent;
变量suggestionsListComponent
没有定义的值,因为您将在下面的条件中分配它们:
自动完成.js
if (showSuggestions && userInput) {
if (filteredSuggestions.length) {
suggestionsListComponent = (
<ul class="suggestions">
{filteredSuggestions.map((suggestion, index) => {
let className;
// Flag the active suggestion with a class
if (index === activeSuggestion) {
className = "suggestion-active";
}
return (
<li className={className} key={suggestion} onClick={onClick}>
{suggestion}
</li>
);
})}
</ul>
);
} else {
suggestionsListComponent = (
<div class="no-suggestions">
<em>No suggestions available.</em>
</div>
);
}
}
第一个条件将检查属性上的值是否showSuggestions
and userInput
存在,而以下条件将检查长度filteredSuggestions
财产。如果满足条件,则suggestionsListComponent
变量为自己分配迭代的值filteredSuggestions
属性,如果索引与中的值匹配,则用类名标记一个活动建议activeSuggestion
财产。这suggestionsListComponent
变量将在执行时返回建议的有序列表onClick
方法,并为每个建议分配一个类名。如果属性上的值showSuggestions
and userInput
不存在,将会出现一条文本,表示不存在,没有可用的建议。
如果用户不满足列出的条件,render()
生命周期方法将返回一个 ReactFragment
应用输入字段并调用方法,而不向文档对象模型添加额外的节点:
自动完成.js
return (
<Fragment>
<input
type="text"
onChange={onChange}
onKeyDown={onKeyDown}
value={userInput}
/>
{suggestionsListComponent}
</Fragment>
);
}
}
export default Autocomplete;
现在你已经开发了你的Autocomplete
组件,导出文件将其功能合并到另一个组件中。
The App
组件是您显示功能的地方Autocomplete
成分。在你的index.js
文件,声明一个App
组件并导入您的Autocomplete
成分:
index.js
import React from "react";
import Autocomplete from "./Autocomplete";
function App() {
return (
<div>
<h1>React Autocomplete Demo</h1>
<h2>Start typing and experience the autocomplete wizardry!</h2>
<Autocomplete suggestions={"Oranges", "Apples", "Banana", "Kiwi", "Mango"]}/>
</div>
);
}
export default App
您的 return 语句App
组件接受Autocomplete
具有固定建议列表的组件。
完成你的Autocomplete
组件,使用 CSS 添加样式来定位应用程序和输入字段并为其着色。
创建一个styles.css
文件并设置 CSS 规则来塑造您的Autocomplete
成分:
样式.css
body {
font-family: sans-serif;
}
input {
border: 1px solid #999;
padding: 0.5rem;
width: 300px;
}
.no-suggestions {
color: #999;
padding: 0.5rem;
}
.suggestions {
border: 1px solid #999;
border-top-width: 0;
list-style: none;
margin-top: 0;
max-height: 143px;
overflow-y: auto;
padding-left: 0;
width: calc(300px + 1rem);
}
.suggestions li {
padding: 0.5rem;
}
.suggestion-active,
.suggestions li:hover {
background-color: #008f68;
color: #fae042;
cursor: pointer;
font-weight: 700;
}
.suggestions li:not(:last-of-type) {
border-bottom: 1px solid #999;
}
构建 CSS 规则后,将文件导入到您的Autocomplete.js
文件来应用您的样式。
React 提供了一些措施来构建一个组件中可用的自动完成功能,并使用内置和自定义方法与用户进行交互。
查看自动完成组件如何运行代码沙箱.