javascript - React Bootstrap Typeahead 指定输入字段中字符的长度
问题描述
第一个问题:为什么,如果我在输入中输入一个字母,console.log (this.state.results.length)
不显示我1
。输入两个字母后才console.log (this.state.results.length)
显示给我2
。
第二个问题:我将输入三个字母,然后删除两个字母,console.log (this.state.results.length)
应该显示我1
和显示2
。当我清除它应该显示的输入时也是如此0
;
此处演示:https ://stackblitz.com/edit/react-frleaq
class App extends Component {
constructor() {
super();
this.state = {
results: ''
};
}
_handleSearch = query => {
this.setState({
results: query
})
}
render() {
console.log(this.state.results.length)
return (
<div>
<AsyncTypeahead
clearButton
id="basic-example"
labelKey="name"
onSearch={this._handleSearch}
/>
</div>
);
}
}
解决方案
您可以使用onInputChange
来处理文本更改,并且可以将文本保持在状态。这样你就可以检查它的长度并做任何你想做的事情。
例子:
import React from "react";
import { AsyncTypeahead } from "react-bootstrap-typeahead";
import "bootstrap/dist/css/bootstrap.css";
import "react-bootstrap-typeahead/css/Typeahead.css";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: false,
multiple: true,
options: [],
selectedUsers: [],
currentInput: ""
};
}
handleSearch = query => {
this.setState({ isLoading: true });
fetch(
`https://api.github.com/search/users?q=${query}+in:login&page=1&per_page=3`
)
.then(resp => resp.json())
.then(({ items }) => {
const options = items.map(i => ({
id: i.id,
name: i.login
}));
return { options };
})
.then(({ options }) => {
this.setState({
isLoading: false,
options
});
});
};
handleChange = selectedItems => {
this.setState({
selectedUsers: selectedItems,
currentInput: ""
});
};
handleInputChange = input => {
this.setState({
currentInput: input
});
};
render() {
const { selectedUsers, isLoading, options, currentInput } = this.state;
return (
<div>
<AsyncTypeahead
clearButton
id="basic-example"
isLoading={isLoading}
options={options}
minLength={3}
multiple
labelKey="name"
onSearch={query => this.handleSearch(query)}
onChange={selectedItems => this.handleChange(selectedItems)}
onInputChange={input => this.handleInputChange(input)}
placeholder="Search for users"
/>
<hr />
<br/>
<br/>
<br/>
{currentInput.length > 0 && <button>MY BUTTON</button>}
<hr />
Selected {selectedUsers.length} Users: <br />
<ul>
{selectedUsers.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
}
export default App;
推荐阅读
- python - & 带数字的运算符
- powershell - 在 Powershell 中根据大小重命名文件
- dictionary - 为什么我的条件只消除字典中的第一个键/值对?
- php - 无法从 Guzzle EntityBody 获取响应正文
- javascript - 如何将特定行从一个电子表格拉到另一个,更新它然后在原始工作表上替换它
- excel - 为什么 CELL("Width", A1) 用“FALSE”填充右侧的单元格?
- node.js - 无法在 firebase 存储桶中创建文件夹 - firebase 管理员
- java - [java]我创建了一个添加类,它可以编译但没有任何东西添加到数组列表中
- angular - 来自html的角度过滤数据
- excel - 如何在 MS Excel 折线图中为每个不同的产品设置不同的水平(类别)标签