TouchableOpacity和TextInput在位于以下位置的视图内不起作用:“绝对”

如何解决TouchableOpacity和TextInput在位于以下位置的视图内不起作用:“绝对”

我有一个自定义下拉菜单,其中下拉视图绝对定位。当组件直接位于滚动视图内部时,我将无法执行文本输入和可触摸操作。

自定义组件代码:

import React,{ Component } from 'react';
import { View,Text,StyleSheet,TouchableOpacity,ScrollView,TextInput } from 'react-native';
import Icon_Feather from 'react-native-vector-icons/Feather';
import Icon_MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import PropTypes from 'prop-types';
import _ from 'lodash';

let dropDownData = []

class MultiSelectDropdown extends Component {

    constructor(props) {
        super(props);

        this.state = {
            isVisible: false,data: [],searchData: [],selectedData: [],// selectAllStatus: false,searchableText: null,defaultSelectedValues: ''
        }
    }

    UNSAFE_componentWillReceiveProps = async (props) => {
        await this.setState({
            data: props.data,defaultSelectedValues: props.selectedData != undefined ? props.selectedData : [],isVisible: props.isVisible
        })
        // alert(this.state.data)
        await this.formatReceivedData()
    }

    formatReceivedData = async () => {
        var pushedData = []
        let tempData = JSON.parse(JSON.stringify(this.state.data))
        tempData.forEach(element => {
            let obj = element
            Object.assign(obj,{ selected: false })
            pushedData.push(obj)
        });

        await this.setState({
            selectedData: pushedData,searchData: pushedData,})

        if (this.state.defaultSelectedValues.length > 0)
            await this.checkDefaultValues();
    }

    checkDefaultValues = async () => {
        this.state.data.forEach((ele1,index1) => {
            this.state.defaultSelectedValues.forEach((ele2,index2) => {
                if (_.isEqual(ele1,ele2)) {
                    this.state.selectedData[index1].selected = true
                    this.setState({
                        selectedData: this.state.selectedData
                    })
                }
            });
        });
    }

    getLayout(layout) {
        this.setState({
            top: layout.height - 1
        });
    }

    toggle() {
        // this.setState({
        //     isVisible: ! this.state.isVisible,// },() => {
        //     const isVisible = this.state.isVisible;

        //     // if (isVisible) {
        //  //  this.props.onOpen();
        //  // } else {
        //  //  this.props.onClose();
        //  // }
        // });
        this.setState({
            isVisible: !this.state.isVisible,})
    }

    selectItem = async (data,index) => {
        var tempSelectedData = this.state.selectedData

        if (tempSelectedData[index].selected == false)
            tempSelectedData[index].selected = true
        else
            tempSelectedData[index].selected = false

        var truePropertyData = tempSelectedData.filter((item) => {
            return item.selected != false
        })

        if (truePropertyData.length > this.props.maxItemsToSelect) {
            // max
            tempSelectedData[index].selected = false;
            var truePropertyData1 = tempSelectedData.filter((item) => {
                return item.selected!= false
            })
            this.removeExtraAddedProperty(truePropertyData1,index);
        } else {
            this.setState({
                selectedData: tempSelectedData,// selectAllStatus: false
            })
            this.removeExtraAddedProperty(truePropertyData,index);
        }

    }

    getSelectedItemCount = () => {
        var truePropertyData = this.state.selectedData.filter((item) => {
            return item.selected!= false
        })
        return truePropertyData;
    }

    getLabelDisplayText = () => {
        let count = this.getSelectedItemCount().length;
        return this.props.multipleDataSelectedText.replace('%d',count);
    }

    selectAll = async () => {
        var tempSelectedData = JSON.parse(JSON.stringify(this.state.selectedData))

        var status = await this.selectAllOrUnselect()

        // if (this.state.selectAllStatus) {
        if (status) {
            tempSelectedData.forEach((ele,i) => {
                tempSelectedData[i].selected= false
            });
            this.setState({
                selectedData: tempSelectedData,// selectAllStatus: false
            })

            var truePropertyData = tempSelectedData.filter((item) => {
                return item.selected!= false
            })
            this.removeExtraAddedProperty(truePropertyData,0)

        } else {
            tempSelectedData.forEach((ele,i) => {
                tempSelectedData[i].selected= true
            });
            this.setState({
                selectedData: tempSelectedData,// selectAllStatus: true
            })
            this.removeExtraAddedProperty(this.state.selectedData,0)
        }

    }

    removeExtraAddedProperty = (truePropertyData,index) => {
        let tempTruePropertyData = JSON.parse(JSON.stringify(truePropertyData))
        var actualData = []
        if (tempTruePropertyData.length > 0) {
            tempTruePropertyData.forEach(element => {
                var obj = element
                delete obj['selected']
                actualData.push(obj)
            });
        } else
            this.props.onItemChange(truePropertyData,index)

        this.props.onItemChange(actualData,index)
    }

    selectAllOrUnselect = () => {
        var returnStatus;
        var trueFilteredData = this.state.selectedData.filter((item,i) => {
            return item.selected == true
        })

        if (trueFilteredData.length == this.state.selectedData.length)
            returnStatus = true
        else
            returnStatus = false

        return returnStatus;
    }

    updateSearch = async (text) => {
        await this.setState({
            searchableText: text
        })

        let toSearch = (this.state.searchableText).toLowerCase();
        let result = this.state.data.filter(o => o[this.props.displayLabel].toLowerCase().includes(toSearch));

        await this.setState({
            searchData: result
        })
    }

    render() {
        return (
            <View style={[this.props.containerStyle,{
                ...(Platform.OS !== 'android' && {
                    zIndex: this.props.zIndex
                })
            }]}>
                <TouchableOpacity
                    onLayout={(event) => this.getLayout(event.nativeEvent.layout)}
                    onPress={() => this.toggle()}
                    activeOpacity={1}
                    style={[
                        styles.dropDown,this.props.style,this.state.isVisible && styles.noBottomRadius,{
                            flexDirection: 'row',flex: 1
                        }
                    ]}
                >
                    <View style={[styles.dropDownDisplay]}>
                        {/* <Text style={[this.props.labelStyle,{ flex: 1,marginRight: 5 }]}> */}
                        {/* {this.props.placeHolder} {this.getSelectedItemCount().length} */}
                        {/* {this.getSelectedItemCount().length > 0 ?
                                'Under Test'
                            :
                                JSON.stringify(this.state.placeHolder)
                            } */}
                        {/* </Text> */}
                        {this.getSelectedItemCount().length > 0 ?
                            <Text style={[this.props.labelStyle,marginRight: 5 }]}>
                                {this.getLabelDisplayText()}
                            </Text>
                            :
                            <Text style={[this.props.labelStyle,marginRight: 5 }]}>
                                {this.props.placeHolder} {JSON.stringify(this.state.isVisible)}
                            </Text>
                        }
                    </View>

                    <View style={[styles.arrow]}>
                        {!this.state.isVisible ?
                            <Icon_Feather name="chevron-down" size={15} color={'black'} />
                            :
                            <Icon_Feather name="chevron-up" size={15} color={'black'} />
                        }
                    </View>

                </TouchableOpacity>

                <View style={[
                    styles.dropDown,styles.dropDownBox,this.props.dropDownStyle,!this.state.isVisible && styles.hidden,{
                        top: this.state.top,maxHeight: this.props.dropDownMaxHeight,zIndex: this.props.zIndex
                    }
                ]}>

                    {/* Search Text */}
                    <View style={{ width: '100%',flexDirection: 'row' }}>
                        <TextInput
                            style={[styles.input,this.props.searchableStyle]}
                            defaultValue={this.state.searchableText}
                            placeholder={this.props.searchablePlaceholder}
                            onChangeText={(text) => this.updateSearch(text)}
                        />
                    </View>

                    <ScrollView style={{ width: '100%' }} nestedScrollEnabled={true}>
                        {this.state.searchData.length > 0 ? this.state.searchData.map((item,index) => (
                            <View key={index}>
                                <TouchableOpacity
                                    style={[styles.dropDownItem,this.props.itemStyle]}
                                    onPress={() => this.selectItem(item,index)}
                                >
                                    <View style={{ flexDirection: 'row' }}>
                                        <View style={{ paddingRight: 5 }}>
                                            {(this.state.selectedData[index] != undefined && this.state.selectedData[index].selected == true) ?
                                                <Icon_MaterialIcons name={'check-box'} size={22} color={'black'} />
                                                :
                                                <Icon_MaterialIcons name={'check-box-outline-blank'} size={22} color={'black'} />
                                            }
                                        </View>
                                        <View style={{ justifyContent: 'center',alignItems: 'center' }}>
                                            <Text style={[this.props.labelStyle]}>
                                                {item[this.props.displayLabel]}
                                            </Text>
                                        </View>
                                    </View>
                                </TouchableOpacity>
                            </View>
                        ))
                            :
                            <Text>
                                Not Found
                            </Text>
                        }
                    </ScrollView>

                </View>
            </View >
        );
    }
}

MultiSelectDropdown.defaultProps = {
    containerStyle: {},style: {},zIndex: 5000,placeHolder: 'Select an option',labelStyle: {},dropDownStyle: {},dropDownMaxHeight: 250,itemStyle: {},displayLabel: '',searchableStyle: {},searchablePlaceholder: 'Search',multipleDataSelectedText: '%d items have been selected',data: PropTypes.array.isRequired,maxItemsToSelect: '',isVisible: false,selectAllText: 'Select All',unselectAllText: 'Un-Select All'
}

MultiSelectDropdown.propTypes = {
    containerStyle: PropTypes.object,style: PropTypes.object,zIndex: PropTypes.number,placeHolder: PropTypes.string,labelStyle: PropTypes.object,dropDownStyle: PropTypes.object,dropDownMaxHeight: PropTypes.number,itemStyle: PropTypes.object,displayLabel: PropTypes.string,searchableStyle: PropTypes.object,isVisible: PropTypes.bool,searchablePlaceholder: PropTypes.string,selectedData: PropTypes.any,multipleDataSelectedText: PropTypes.string,maxItemsToSelect: PropTypes.string,selectAllText: PropTypes.string,unselectAllText: PropTypes.string
}

const styles = StyleSheet.create({
    container: {
        flex: 1,backgroundColor: 'white',},noBottomRadius: {
        borderBottomLeftRadius: 0,borderBottomRightRadius: 0,dropDown: {
        paddingHorizontal: 10,paddingVertical: 5,backgroundColor: '#fff',borderTopRightRadius: 5,borderTopLeftRadius: 5,borderBottomRightRadius: 5,borderBottomLeftRadius: 5,borderWidth: 1,borderColor: '#dfdfdf',dropDownDisplay: {
        flexDirection: 'row',alignItems: 'center',borderTopRightRadius: 0,flexGrow: 1
    },arrow: {
        flexDirection: 'row',justifyContent: 'center',textAlign: 'center',paddingVertical: 8,borderTopLeftRadius: 0,borderBottomLeftRadius: 0,dropDownBox: {
        borderTopLeftRadius: 0,position: 'absolute',width: '100%',zIndex: 1
    },hidden: {
        position: 'relative',display: 'none',borderWidth: 0
    },dropDownItem: {
        paddingVertical: 8,justifyContent: 'center'
    },input: {
        flex: 1,borderBottomWidth: 1,paddingHorizontal: 0,marginBottom: 2,});

export default MultiSelectDropdown;

上面的组件在视图中使用时可以正常工作,但是当将其放置在模式中时则无法工作。即我无法执行触摸和文本输入操作。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-