按下空格键后,我的 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
示例,那里实现的输入框也不允许空格。
我有办法解决这个问题吗? 谢谢。
最佳答案
代码甚至还不错,但不是最优的(特别是对于学习海豚)。
您可能正在寻找的是在用户键入时可视化输入中的值:
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>
);
}
}
关于html - 在 <input> 上使用 onChange 时未注册空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56331518/