html - 使用 onChange on 时未注册的空间
问题描述
按下空格后,我的 html 输入元素上没有调用 onChange 事件。
这是我尝试过的。
class FilterDropDown extends React.PureComponent {
state = {
query: '',
};
handleKeyPress = (evt) => {
this.setState({ query: evt.target.value });
};
render() {
const { placeholder, items, id } = this.props;
return (
<DropDown
placeholder={placeholder}
open={this.state.show}
onToggle={this.disableAppScrollAndToggleShowState}
onSelect={this.onSelect}
value={this.props[id]}
>
{
this.props.filterable
&& (
// eslint-disable-next-line react/jsx-no-undef
<DropDown.Item disabled className="filters__option-text-filter">
<div className="wrapper">
<Label className="filter-dropdown__search-icon" />
<input
type="text"
onChange={this.handleKeyPress}
size="sm"
placeholder={this.props.filterPlaceholder}
aria-label="filter-dropdown"
value={this.state.query}
/>
<Button className="filter-dropdown__clear" onClick={this.resetQuery} />
</div>
</DropDown.Item>
)
}
{
items
.filter(item => item.value.length > 0
&& item.value.toLowerCase().includes(this.state.query.toLowerCase()))
.map(item => (
<DropDown.Item
active={item.value === this.props[id]}
key={item.value}
eventKey={item.value}
>
<span className="filter-options">{`${item.value} (${item.count})`}</span>
</DropDown.Item>
))
}
</DropDown>
);
}
}
我没有发布整个代码,但足以理解使用。此外,此输入字段位于React Bootstraps Dropdown
元素内,不允许输入接受空格。
这是 react Dropdown 文档的链接https://react-bootstrap.github.io/components/dropdowns/
。如果我们看一下Custom Dropdown Components
例子,那里实现的输入框也不允许空格。
有什么办法可以解决吗?谢谢。
解决方案
代码甚至很好,不是最优的(特别是对于学习 porpuses)。
您正在寻找的可能是在用户键入时可视化输入中的值:
import React from 'react';
class MyComponent extends React.Component {
state = {
query: '',
}
handleKeyPress = (evt) => {
this.setState({ query: evt.target.value }, () => {
console.log("query: " + this.state.query) // this is for debugging
});
};
render() {
return (
<div>
<input type="text"
onChange={this.handleKeyPress}
size="sm"
placeholder={this.props.filterPlaceholder}
aria-label="filter-dropdown"
value={this.state.query}
/>
<h1>query: {this.state.query}</h1>
{/* this is for visualing the changes in the component*/}
</div>
);
}
}
推荐阅读
- omnet++ - 错误:由于缺少基本类型或接口,无法完全解析 NED 类型“myApp”?
- c# - 有没有更好的方法来编写我的物品/武器解锁系统?
- tensorflow - 安装 Tensorflow-gpu 后出现错误 Failed to load the native TensorFlow runtime
- ios - UIView 展开到 Content 里面
- javascript - jQuery如何更改每个表数据行的类?
- javascript - 如何循环数组以显示表中所有行的所有数据?
- angular - 如何通过 ng update 将 Angular 7 更新到 Angular 8
- java - 由于自定义约束验证器,验证器单元测试失败
- javascript - Ajax 不更新数据库中的属性
- java - 尝试通过反射访问内部类构造函数的参数注释时出现 ArrayIndexOutOfBoundsException