我是 React Native 的新手,我一直在研究一个搜索栏,它可以在用户输入字段时过滤列表。这是它的样子......
<TextInput style={{width: '100%', textAlign: 'center'}}
ref={(ref) => this.searchInput = ref}
placeholder="Search"
onChangeText={ (text) => this.onChangeText(text)}
value={this.state.search} />
Run Code Online (Sandbox Code Playgroud)
这是我用于此行为的 onChangeText 方法
onChangeText(text) {
var filtered;
this.setState({search: text});
filtered = this.props.data.filter((item) => {
if(item.section) {
return true;
}
return (item.label.toLowerCase().includes(text.toLowerCase()));
});
this.setState({filteredList: filtered});
}
Run Code Online (Sandbox Code Playgroud)
我已将状态设置为保留用户在搜索栏中输入的任何内容,因为它会在渲染时清除。这工作正常,除了每次组件重新渲染时键盘一直关闭(在用户输入/删除的每个字符上)。
为了解决这个问题,我尝试使用像这样的 refs 专注于输入
componentDidUpdate() {
if(this.searchInput) {
this.searchInput.focus();
}
}
Run Code Online (Sandbox Code Playgroud)
但即便如此,键盘还是会时不时地播放打开/关闭动画,并且无法顺利处理输入/删除操作。
为了解决这个问题,我想将 TextInput 移动到一个单独的组件中(只有那个输入字段),然后将该组件添加到我的列表中。但是,我必须不断地将文本数据传回以过滤我的列表,从而增加了更多的复杂性。可能有更简单的解决方案吗?