单击复选框后,将复选框的值添加到数组中

时间:2018-07-17 04:31:59

标签: javascript reactjs react-native

在这种情况下,我想将用户ID转移到State中定义的数组。

当我单击复选框以将其选中时,我想这样做,而当我取消选中该复选框时,我想从阵列中删除用户ID

import React, { Component } from "react";
import { 
    View,
    Text,
    StyleSheet,
    FlatList,
    AsyncStorage
    } from "react-native";
import axios from 'axios';
import { Button, Container, Content, Header, Body, Left, Right, Title } from 'native-base';
import Icon from 'react-native-vector-icons/Ionicons';
import { List, ListItem, SearchBar, CheckBox } from "react-native-elements";
    
    // const itemId = this.props.navigation.getParam('itemId', 'NO-ID');
    // const otherParam = this.props.navigation.getParam('otherParam', 'some default value');

    class TeacherSubjectSingle extends Component{
        static navigationOptions = {
            header : null
        }
        // static navigationOptions = {
        //     headerStyle: {
        //         backgroundColor: '#8E44AD',
        //       },
        //     headerTintColor: '#fff',
            
        // }

        state = {
            class_id: null,
            userid: null,
            usertype: null,
            student_list: [],
            faq : [],
            checked: [],
        }

        componentWillMount = async () => {
            const {class_id, student_list, userid, usertype} = this.props.navigation.state.params;
            await this.setState({
                class_id : class_id,
                student_list : student_list,
                userid : userid,
                usertype : usertype,
            })
            console.log(this.state.class_id)
            var result = student_list.filter(function( obj ) {
                return obj.class_section_name == class_id;
              });
            this.setState({
                student_list: result[0]
            })
            
        }

        renderSeparator = () => {
            return (
              <View
                style={{
                  height: 1,
                  width: "100%",
                  backgroundColor: "#CED0CE",
                }}
              />
            );
        };

        checkItem = (item) => {
            const { checked } = this.state;
            console.log(item)
            if (!checked.includes(item)) {
              this.setState({ checked: [...checked, item] });
              
            } else {
              this.setState({ checked: checked.filter(a => a !== item) });
            }
            console.log(checked)
        };

        render(){
            
            return (
                <Container>
                    <Header style={{ backgroundColor: "#8E44AD" }}>
                        <Left>
                            <Button transparent onPress={()=> this.props.navigation.navigate('ClassTeacher')}>
                                <Icon name="ios-arrow-dropleft" size={24} color='white' />
                            </Button>
                        </Left>
                        <Body>
                            <Title style={{ color: "white" }}>{this.state.class_id}</Title>
                        </Body>
                        <Right>
                            {this.state.checked.length !== 0 ? <Button transparent onPress={()=> this.props.navigation.navigate('ClassTeacher')}>
                                <Text>Start Chat</Text>
                            </Button> : null}
                        </Right>
                    </Header>
                    <View style={{flex: 1, backgroundColor: '#fff'}}>
                    <List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}>
                    <FlatList
                        data={this.state.student_list.students}
                        extraData={this.state.checked}
                        renderItem={({ item }) => (
                        <ListItem
                            // roundAvatar
                            title={<CheckBox
                            title={item.name}
                            checkedColor='#8E44AD'
                            onPress={() => this.checkItem(item.userid)}
                            checked={this.state.checked.includes(item.userid)}
                            />}
                            // subtitle={item.email}
                            // avatar={{ uri: item.picture.thumbnail }}
                            //containerStyle={{ borderBottomWidth: 0 }}
                            onPress={()=>this.props.navigation.navigate('IndividualChat', {
                            rc_id: item.userid,
                            userid: this.state.userid,
                            usertype: this.state.usertype,
                            subject_name: this.state.student_list.subject_name
                            })}
                        />
                        )}
                        keyExtractor={item => item.userid}
                        ItemSeparatorComponent={this.renderSeparator}
                        
                    />
                    </List>
                    </View>
                </Container>
            );
        }
    }
export default TeacherSubjectSingle;

const styles = StyleSheet.create({
    container:{
    flex:1,
    alignItems:'center',
    justifyContent:'center'
    }
});

这是相同的代码,我为相同的对象创建了一个函数checkItem()并且可以正常工作,唯一的问题是,当我单击第一个项目时,它将输出空白数组,选择第二项,它将返回包含第一项的数组,依此类推。请帮助我解决它,谢谢

3 个答案:

答案 0 :(得分:2)

尝试以下代码:

  checkItem = (e) => {
   let alreadyOn = this.state.checked; //If already there in state

    if (e.target.checked) {
      alreadyOn.push(e.target.name); //push the checked value
    } else {
       //will remove if already checked
      _.remove(alreadyOn, obj => {
        return obj == e.target.name;
      });
    }
    console.log(alreadyOn)
    this.setState({checked: alreadyOn});
}

答案 1 :(得分:1)

这是因为您是在setState之后立即打印this.state.checked值,而setState是异步的,因此不会立即更新状态值。 您可以使用setState回调方法来检查更新的状态值。

这样写:

checkItem = (item) => {
    const { checked } = this.state;
    let newArr = [];

    if (!checked.includes(item)) {
        newArr = [...checked, item];
    } else {
      newArr = checked.filter(a => a !== item);
    }
    this.setState({ checked: newArr }, () => console.log('updated state', newArr))
};

检查此答案以获取有关setState的更多详细信息:

Why calling setState method doesn't mutate the state immediately?

答案 2 :(得分:0)

类似,带有事件侦听器和数组的.push方法。

var checkboxes = document.querySelectorAll('input[type=checkbox]'); 
var myArray = [];
for (var i = 0; i < checkboxes.length; i++) {
    checkboxes[i].addEventListener("click", function(e) {
      myArray.push(e.target.value);
      console.log(myArray);
    });
};
<div>
    <input type="checkbox" name="feature" value="scales" />
    <label >Scales</label>
</div>

<div>
    <input type="checkbox" name="feature" value="horns" />
    <label >Horns</label>
</div>

<div>
    <input type="checkbox" name="feature" value="claws" />
    <label >Claws</label>
</div>

相关问题