我有一个平面列表
<View style={styles.container}>
<FlatList data={this.state.restaurants}
renderItem={({ item }) => this.renderItem(item.restaurant)}
keyExtractor={restaurant => restaurant.key}
ListHeaderComponent={() => this.renderHeaderComponent()}
ItemSeparatorComponent={this.renderSeparator}/>
</View>
并在标题中包含 TextInput。我使用 TextInput 作为搜索栏。
renderHeaderComponent() {
return(
<View style={{ flexDirection: 'row', marginTop: 10, borderBottomColor: '#CED0CE', borderWidth: 1, borderColor: 'transparent' }}>
<Icon name='search' size={30} style={{ marginLeft: 10, marginRight: 10 }}/>
<TextInput
style={{height: 40, flex: 1}}
onChangeText={(text) => this.onChangeText(text)}
placeholder='Type text for search'
clearButtonMode='while-editing'
value={this.state.searchText}
/>
</View>
);
};
在 onChangeMethod 中我过滤我的数据。
onChangeText(text) {
const filteredRestaurants = _.filter(this.props.list, (restaurantObject) => {
const restaurant = restaurantObject.restaurant;
const result = restaurant.name.trim().toLowerCase().includes(text.trim().toLowerCase());
return result;
})
this.setState({
searchText: text,
restaurants: filteredRestaurants
});
}
问题如下。当我在 TextInput 中键入一个符号时,焦点会立即从 TextInput 丢失吗?如何在键入时将注意力集中在 TextInput 中?
最佳答案
你需要为此使用一个auto-bound
方法,因为ListHeaderComponent
是ReactClass
类型,而你当前的方法基本上重新-每次数据更新时创建并重新绑定(bind)其 render
,这不是您想要的。 this comment 中进一步解释了这个概念。
无论如何,对于您的示例,要解决您的问题,您应该
1) 将您的 ListHeaderComponent
属性更改为
ListHeaderComponent={this.renderListHeader}
2) 现在您想要将renderHeaderComponent
方法更改为自动绑定(bind)方法
,这样每次更改时都不会实例化一个新的渲染器数据(或在 `TextInput 中输入文本)
renderListHeader = () => (
<View style={{ flexDirection: 'row', marginTop: 10, borderBottomColor: '#CED0CE', borderWidth: 1, borderColor: 'transparent' }}>
<Icon name='search' size={30} style={{ marginLeft: 10, marginRight: 10 }}/>
<TextInput
style={{height: 40, flex: 1}}
onChangeText={(text) => this.onChangeText(text)}
placeholder='Type text for search'
clearButtonMode='while-editing'
value={this.state.searchText}
/>
</View>
)
关于javascript - 搜索时键入一个符号后 TextInput 失去焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46948235/