javascript - 搜索时键入一个符号后 TextInput 失去焦点

标签 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>

并在标题中包含 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方法,因为ListHeaderComponentReactClass类型,而你当前的方法基本上重新-每次数据更新时创建并重新绑定(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/

相关文章:

javascript - d3.js 时间刻度图表,数组对象值不渲染图表,而静态值完美渲染图表

reactjs - 通过在 React 中更改父组件的 Props 来更新子组件

javascript - React Native iOS WebView在本地html中执行javascript标签

javascript - 我如何判断 Realm 是否已成功更新?

reactjs - iOS DatePicker 在 React Native 中不显示

javascript - Canvas 不全屏显示

javascript - angularjs 子指令 DOM 加载速度不够快

css - React Native 中的颜色文字有什么问题?

javascript - 在这种特定情况下没有 Accordion 效果的 Accordion 菜单

javascript - 为我的 React typescript 项目配置 Webpack(Webpack 版本 4.39.2)