【发布时间】:2019-04-12 22:54:29
【问题描述】:
作为技术测试的一部分,我被要求在 React 中编写一个自动完成输入。我已经完成了这项工作,但我现在想添加使用箭头键在渲染列表上上下导航的功能。我做了一些广泛的谷歌搜索,除了 npm 包之外没有发现任何特定于 React 的内容。
明确地说,我正在寻找类似的东西,但对于 React:https://www.w3schools.com/howto/howto_js_autocomplete.asp
我基本上只需要箭头按钮功能,其他一切正常。
干杯
这是我尝试但无法正常工作的示例。
export default class Example extends Component {
constructor(props) {
super(props)
this.handleKeyDown = this.handleKeyDown.bind(this)
this.state = {
cursor: 0,
result: []
}
}
handleKeyDown(e) {
const { cursor, result } = this.state
// arrow up/down button should select next/previous list element
if (e.keyCode === 38 && cursor > 0) {
this.setState( prevState => ({
cursor: prevState.cursor - 1
}))
} else if (e.keyCode === 40 && cursor < result.length - 1) {
this.setState( prevState => ({
cursor: prevState.cursor + 1
}))
}
}
render() {
const { cursor } = this.state
return (
<Container>
<Input onKeyDown={ this.handleKeyDown }/>
<List>
{
result.map((item, i) => (
<List.Item
key={ item._id }
className={cursor === i ? 'active' : null}
>
<span>{ item.title }</span>
</List.Item>
))
}
</List>
</Container>
)
}
}
这是我的代码:
class Search extends Component {
constructor(props) {
super(props);
this.state = {
location: '',
searchName: '',
showSearch: false,
cursor: 0
};
}
handleKeyPress = e => {
const { cursor, searchName } = this.state;
// arrow up/down button should select next/previous list element
if (e.keyCode === 38 && cursor > 0) {
this.setState(prevState => ({
cursor: prevState.cursor - 1
}));
} else if (e.keyCode === 40 && cursor < searchName.length - 1) {
this.setState(prevState => ({
cursor: prevState.cursor + 1
}));
}
};
render() {
const { searchName, location } = this.state;
return (
<div className="Search">
<h1>Where are you going?</h1>
<form id="search-form" onSubmit={this.handleSubmit}>
<label htmlFor="location">Pick-up Location</label>
<input
type="text"
id="location"
value={location}
placeholder="city, airport, station, region, district..."
onChange={this.handleChange}
onKeyUp={this.handleKeyUp}
onKeyDown={this.handleKeyPress}
/>
{this.state.showSearch ? (
<Suggestions searchName={searchName} />
) : null}
<button value="submit" type="submit" id="search-button">
Search
</button>
</form>
</div>
);
}
从 RESTful API 呈现列表的代码:
.then(res =>
this.setState({
searchName: res.data.results.docs.map(array => (
<a href="#">
<div
key={array.ufi}
className="locations"
>
{array.name}
</div>
</a>
))
})
);
【问题讨论】:
-
您是否尝试过实现您想要的箭头功能?请发布您尝试过的代码
-
我已经尝试了一些我在这里找到的东西,但没有奏效。我现在将发布我的代码。
-
创建函数
handleKeyDown为handleKeyDown = (e) => ...,或使用onKeyDown={this.handleKeyDown.bind(this)}为函数获取正确的this上下文 -
试过了,但还是不能让它循环。
标签: javascript reactjs autocomplete