【问题标题】:Function inside a FlatList item does not fire when passing the renderItem as prop to the component将 renderItem 作为 prop 传递给组件时,FlatList 项内的函数不会触发
【发布时间】:2020-04-02 07:13:10
【问题描述】:

当按下 FlatList 组件内的列表项时,不会触发 onPress 事件。我有一个使用Autocomplete 组件的主要组件。这个Autocomplete 组件由TextInputFlatList 组成View

//Autocomplete component
//...
return (
    <View>
        <TextInput
            value={props.value}
            onChangeText={props.onChangeText}
            onFocus={props.onFocus}
            onBlur={props.onBlur}
        />
        <FlatList
            data={props.data}
            keyExtractor={item => item.id}
            renderItem={props.renderItem}/>
    </View>
)

主组件向Autocomplete组件传递了一个renderItem prop,我想在其中按下列表上的一个项目时调用一个函数:

//main component
//...
const selectHandler = (item) => {
    console.log("test")
};

return(
<Autocomplete
    data={filteredData}
    value={searchTerm}
    renderItem={itemData => (
        <TouchableOpacity
            onPress={(item) => selectHandler(item)}>
            <Text>
                some text
            </Text>
        </TouchableOpacity >
    )}
    onChangeText={text => setSearchTerm(text)}
    onFocus={focusHandler}
    onBlur={blurHandler}
/>
)

但是,这个console.log("test") 永远不会触发。这可能是什么原因?

【问题讨论】:

    标签: reactjs react-native event-handling react-native-flatlist


    【解决方案1】:

    在 FlatList 中尝试renderItem={() =&gt; props.renderItem}/&gt;

    【讨论】:

      【解决方案2】:

      我找到了原因。因为在使用TextInput I need to add keyboardShouldPersistTaps={'handled'}FlatList 组件时键盘是打开的。最初我没有看到我必须单击两次,因为我的Autocomplete 组件消失了onBlur,我认为onPress 事件根本不起作用。

      【讨论】:

        猜你喜欢
        • 2023-04-05
        • 2023-02-17
        • 2019-09-29
        • 2019-05-16
        • 2023-04-03
        • 2023-01-08
        • 1970-01-01
        • 2023-01-11
        • 1970-01-01
        相关资源
        最近更新 更多