Ale*_*lov 6 javascript reactjs react-native redux react-redux
我有一个平面列表
<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>
Run Code Online (Sandbox Code Playgroud)
并在标题中包含 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>
);
};
Run Code Online (Sandbox Code Playgroud)
在 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
});
}
Run Code Online (Sandbox Code Playgroud)
问题如下。当我在 TextInput 中输入一个符号时,TextInput 会立即失去焦点吗?打字时如何将焦点放在 TextInput 上?
您需要为此使用一个auto-bound方法,就像ListHeaderComponenttype 一样ReactClass,并且您当前的方法基本上render每次数据更新时都会重新创建并重新绑定它,这不是您想要的。这个概念在这个评论中有进一步的解释
无论如何,对于您的示例,要解决您的问题,您应该
1)将您的ListHeaderComponent道具更改为
ListHeaderComponent={this.renderListHeader}
2)现在你想把你的renderHeaderComponent方法改成一个auto-bound method,这样一来,每次更改数据时都不会实例化一个新的渲染(或者在`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>
)
Run Code Online (Sandbox Code Playgroud)
小智 5
我遇到了这个问题,为了解决这个问题,我将 renderListHeader 包装在 React.useMemo 挂钩中,并将状态挂钩作为项目传递给依赖项数组。
renderListHeader = useMemo(() => (
<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>
), [this.onChangeText])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2244 次 |
| 最近记录: |