javascript - 如何使用 React Native 中的 React Native 元素库中的复选框从平面列表中选择多个项目?

标签 javascript node.js react-native ecmascript-6

我正在创建一个带有复选框和文本的平面列表,但我要选择一个项目,它会从列表中选择所有项目,我想选择单个或多个或所有项目,但不是全部这样,当我选择单个项目,它检查所有项目。 我在这里从 api 获取列表。 这是我的代码:

import React, { Component } from 'react'
import { View,FlatList} from 'react-native'
import { HeaderView } from '../components/Headers';
import { color } from '../values/color';
import TextViewClickable, { TextViewNonClickable } from     
    '../components/TextView';
import { dimension } from '../values/dimensions';
import Modal from 'react-native-modal';
import { Header, Icon, CheckBox, Button } from 'react-native-
    elements';
import { getSessionId, showMessage } from '../utils
    /GeneralFunctions';
import { showMyLists } from '../networkRequest/API';
import { onSuccess, onFailure } from '../networkRequest
    /AxiosRequest';

export default class AllLists extends Component {

constructor(props){
    super(props)
    this.state={
        lists : [],
        isChecked : false
    }
}

componentWillMount() {
    this.getAllList()
}

getAllList = () => {
  //  this.showRefreshLoader();
    getSessionId().then(sessionId => {
    showMyLists(sessionId).then(response => {
        onSuccess(response).then(successResponse => {
    //    this.hideRefreshLoader();
        this.setState({
            lists:successResponse,
        })
        })
    }).catch(error => {
       // this.hideRefreshLoader();
        onFailure(error).then(errorMessage => {
        showMessage(errorMessage);
        })
    })
    })
}

isIconCheckedOrNot = () => {
    if(this.state.isChecked){
        this.setState({isChecked:false})
    }else {
        this.setState({isChecked:true})
    }
}

_renderListItem = ({item}) => {
    return(

        <View style=
     {{flex:1,flexDirection:'row',alignItems:'center',
    justifyContent:'flex-start'}}>
            <CheckBox
                checked={this.state.isChecked}
                onPress={() => this.isIconCheckedOrNot()}
            />
            <TextViewNonClickable
                textViewText={item.name}
                textStyle=
    {{color:color.colorBlack,fontWeight:'700'}}
            />
        </View>
    )
}

//render screen
render() {

const {modalVisibility,closeModal} = this.props;

return (
    <Modal
        animationIn='zoomInDown'
        animationOut='zoomOutDown'
        isVisible={modalVisibility}
        animationInTiming={300}s
        animationOutTiming={300}
        onBackButtonPress={closeModal}
        style={{margin:32}}
    >
        <View style={{alignItems:'flex-start', 
            flex:1,backgroundColor:color.colorWhite}}>
            <Header
                placement='left'
                leftComponent={
                    <Icon name='cross' type='entypo' color='white' 
        iconStyle={{padding:16}} 
                        onPress={closeModal}/>
                    }
                centerComponent={{ text: 'My Lists', 
                    style: [{ color: 
    'white',fontWeight:'bold',fontSize:24 }] }} 
                outerContainerStyles=
    {{alignSelf:'stretch',height:64,borderBottomWidth:0}}
                backgroundColor={color.loginBgColor}
            />
            <FlatList
                data={this.state.lists}
                renderItem={this._renderListItem}
                keyExtractor={(item,index) => item+index}
                style={{flex:1,width:dimension.screenWidth}}
                showsVerticalScrollIndicator={false}
                alwaysBounceVertical
            />
            <Button
                title={'Ok'}
                containerStyle=
    {{position:'absolute',bottom:10,right:10}}
                onPress={closeModal}
                buttonStyle=
    {{paddingHorizontal:16,paddingVertical:8,
    backgroundColor:color.colorAccent}}
            />

        </View>
    </Modal>
    )
  }
}

最佳答案

export default class AllLists extends Component {

constructor(props){
    super(props)
    this.state={
        isChecked : [],
}
}

componentWillMount = () => {
    let initialCheck = this.state.lists.map(() => false);
    this.setState({isChecked : initialCheck})
}

getAllList = () => {
 this.showRefreshLoader();
    getSessionId().then(sessionId => {
        showMyLists(sessionId).then(response => {
            onSuccess(response).then(successResponse => {
            this.hideRefreshLoader();
            this.setState({
                lists:successResponse,
            })
        })
    }).catch(error => {
        this.hideRefreshLoader();
        onFailure(error).then(errorMessage => {
            showMessage(errorMessage);
        })
      })
    })
}

//add product to selected lists 
addProduct = () => {

    showMessage(JSON.stringify(this.state.selectedLists))
    getSessionId().then(sessionId => {
        addProductToLists(sessionId,this.state.selectedLists,
    this.props.productId).then(response => {
            onSuccess(response).then(response => {
                alert(JSON.stringify(response.message))
            })
        }).catch(error => {
            onFailure(error).then(error => {
                alert(JSON.stringify(error))
            })
        })
    })
    }

    isIconCheckedOrNot = (item,index) => {
    let { isChecked,selectedLists} = this.state;
    isChecked[index] = !isChecked[index];
    this.setState({ isChecked : isChecked});
    if(isChecked[index] == true){
        selectedLists.push(item.list_id)
    }else {            
        selectedLists.pop(item.list_id)
    }

    }



    _renderListItem = ({item,index}) => {
    return(            
        <View >
            <CheckBox
                checked={this.state.isChecked[index]}
                onPress={() => this.isIconCheckedOrNot(item,index)}
            />
            <TextViewNonClickable
                textViewText={item.name}
                textStyle={{color:color.colorBlack,fontWeight:'700'}}
            />
        </View>
    )
}

_onOkPress = () => {
    this.props.closeModal();
}

//render screen
render() {

const {modalVisibility,closeModal} = this.props;

return (
    <Modal
        animationIn='zoomIn'
        animationOut='zoomOut'
        isVisible={modalVisibility}
        onBackButtonPress={closeModal}
        style={{margin:32}}
    >
        <View >
             <FlatList
                data={this.state.lists}
                renderItem={this._renderListItem}
                keyExtractor={(item,index) => item+index}
                style={{flex:1,width:dimension.screenWidth}}
                showsVerticalScrollIndicator={false}
                alwaysBounceVertical
                refreshControl = {
                    <RefreshControl
                        refreshing={this.state.isRefreshing}
                        onRefresh={() => {
                            this.getAllList();
                        }}
                    />
                }
            />
            <Button
                title={'Ok'}
                containerStyle={{position:'absolute',bottom:10,right:10}}
                onPress={() => this.addProduct()}

            />                
        </View>
    </Modal>
)
  }
}

关于javascript - 如何使用 React Native 中的 React Native 元素库中的复选框从平面列表中选择多个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53427360/

相关文章:

reactjs - react native MapViewDirections : force entire route to remain in view?

javascript - 通过搜索查找文本并突出显示出现错误

javascript - 正则表达式中的否定

javascript - 我现在有多行字符串,我想打印包含特定子字符串的那些行

javascript - 在 Node.js 服务器上通过 fs 创建文件时出错

javascript - 如何从ajax响应中取出 header

javascript - 根据一天中的时间更改颜色

node.js - 意味着 init 在 "What would you name your mean app?"之后停止

javascript - 如何确保带有promise的函数继续执行

javascript - react native -调试[对象对象]handleException-Observable