【问题标题】:I need to create a new object every time i click on a switch and delete it whenever i switch off每次单击开关时都需要创建一个新对象,并在关闭时将其删除
【发布时间】:2020-05-23 20:15:10
【问题描述】:

TLDR:我需要根据开关的选择创建一个新对象,如果我单击,则该特定项目项将克隆到这个新对象,依此类推

在 reddit 上也有这个问题 -> https://www.reddit.com/r/reactnative/comments/gpvnhv/need_help_creating_a_new_object_based_on_dropdown/

编辑:我设法通过仅获取客户端来过滤下拉组件的对象,还获得了项目的过滤器以显示在平面列表中。我需要通过连接两者来获得帮助,也就是说,从下拉列表中选择一个客户并显示他们获得相同 ID 的所有项目,就像这样

客户名单:

[
  {
    client: 'Microsoft', 
    idClient: '1'
  },
  {
    client: 'Google', 
    idClient: '0'
  }
]

项目列表:

[
  {
    project: 'Random stuff', 
    idClient: '1'
  }, 
  {
    project: 'Another Random stuff', 
    idClient: '1'
  }, 
  {
    project: 'GG', 
    idClient: '0'
  }
]

我一直在头疼试图弄清楚这一点,我得到了一个带有项目/客户的对象,类似这样的。

items = [
 {
  client: 'Microsoft',
  idClient: 0,
  idProjectType: 1,
  projectType: 'traditional',
  title: 'React Native App'
 },
 {
  client: 'Amazon',
  idClient: 1,
  idProjectType: 1,
  projectType: 'traditional',
  title: 'ServerSide OPS'
 },
 {
  client: 'Microsoft',
  idClient: 0,
  idProjectType: 1,
  projectType: 'traditional',
  title: 'AI Enhancer'
 },
 {
  client: 'Google',
  idClient: 4,
  idProjectType: 1,
  projectType: 'traditional',
  title: 'Whatever Come Up With'
 },
 {
  client: 'KFC',
  idClient: 3,
  idProjectType: 1,
  projectType: 'traditional',
  title: 'QR Reader'
 },     
]

这只是我的对象的一个​​示例,它有 20 多个客户,其中一些客户每个可能有大约 3 或 4 个项目,整个对象大约有 60 到 70 个项目。

我有两个屏幕,一个是主屏幕,它为每一天呈现带有自定义视图的日历条,好的,有趣的部分来了,这就是我的问题所在

第二个屏幕是一个下拉菜单,我在其中选择一个客户端并列出基于该选定客户端的所有项目,最大的问题是,由于我无法操作此对象,首先,我需要为每个项目,为了选择我需要在第一个屏幕上显示的项目,第二,新对象需要包含(除了对象中的项目),更多的东西,比如这个 {project: 'React Native App', hoursRemaining: 10, etc...}

这是下拉列表屏幕的完整代码

import * as React from 'react';
import {View, Text, Image, StatusBar, SafeAreaView, TouchableOpacity, ScrollView, RefreshControl, FlatList, Platform} from 'react-native';
import { Header, ListItem } from 'react-native-elements';
import ModalDropdown from 'react-native-modal-dropdown';
import Images from '../../Assets/values/images';
import { RFPercentage as rfp, RFValue as rfv } from 'react-native-responsive-fontsize';
import { heightPercentageToDP as hp, widthPercentageToDP as wp } from 'react-native-responsive-screen';
import styles from '../../Assets/values/styles/HoursReport/ClientsProyects/ClientsProyectsStyle';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import DataManager from '../../../Util/CrossUtils/DataManager';

export default class ClientsProyectsScreen extends React.Component<any, any> {
  constructor(props: any) {
    super(props);

    this.state = {
      SeleccionClientes: '',
    }
  }

    items = [
 {
  client: 'Microsoft',
  idClient: 0,
  idProjectType: 1,
  projectType: 'traditional',
  title: 'React Native App'
 },
 {
  client: 'Amazon',
  idClient: 1,
  idProjectType: 1,
  projectType: 'traditional',
  title: 'ServerSide OPS'
 },
 {
  client: 'Microsoft',
  idClient: 0,
  idProjectType: 1,
  projectType: 'traditional',
  title: 'AI Enhancer'
 },
 {
  client: 'Google',
  idClient: 4,
  idProjectType: 1,
  projectType: 'traditional',
  title: 'Whatever Come Up With'
 },
 {
  client: 'KFC',
  idClient: 3,
  idProjectType: 1,
  projectType: 'traditional',
  title: 'QR Reader'
 },     
]

  componentDidMount(){
    console.log(DataManager.ResponseProjectClient);
  }

  searchCliente = item => {
    var jsonData = item;
    var searchData = [];
    jsonData.forEach(element => {
      searchData.push(element.cliente);
    });
    return searchData;
  }

  searchProyecto = item => {

  }

  updateFav = item => {
   const newData = [...this.items[this.state.SeleccionClientes]];
   const updateItem = newData.find(x => x.key === item.key);
   updateItem.fav = !item.fav;
   const updatedArray = Object.assign(this.items);
   updatedArray[this.state.SeleccionClientes] = newData;
   this.setState({ items: updatedArray });
  };

  render() {
    return (
      <>
        <StatusBar translucent backgroundColor="transparent" />
        <SafeAreaView style={{backgroundColor: '#fafafa'}}/>
        {/*
        <Header
          backgroundImage={Images.header_nav}
          backgroundImageStyle={styles.HeaderImagenCP}
          leftComponent={
            <TouchableOpacity onPress={() => this.props.navigation.goBack()}>
              <View><Image style={styles.HeaderHorizontal} source={Images.back}/></View>
            </TouchableOpacity>
          }
          centerComponent={{text: 'Imputar horas', ellipsizeMode: 'clip', style: styles.HeaderHoursReportCP }}
          placement='center'
        />
        */}
        <View style={styles.ContainerBackground}>
        <View style={{flexDirection: 'row'}}>
          <View style={{alignItems: 'flex-start', justifyContent: 'flex-start', alignSelf: 'flex-start', marginTop: hp('2.2%'), marginLeft: wp('6.3%')}}>
            <Text style={{
              fontSize: rfv(18),
              fontWeight: "500",
              fontStyle: "normal",
              textAlign: "left",
              color: "#707070"
            }}>Proyectos</Text>
          </View>
          <TouchableOpacity style={{position: 'absolute', alignItems: 'flex-end', justifyContent: 'flex-end', alignSelf: 'flex-end', paddingBottom: hp('1%'), left: wp('90%')}} onPress={() => this.props.navigation.goBack()}>
            <Image source={Images.close_modal}/>
          </TouchableOpacity>
        </View>
        <KeyboardAwareScrollView
          keyboardShouldPersistTaps="handled"
          enableOnAndroid={true}>
            {/*
            <View style={{alignItems: 'flex-end', justifyContent: 'flex-end', alignSelf: 'flex-end', marginRight: widthPercentageToDP('6.3%')}}>
              <TouchableOpacity onPress={() => this.props.navigation.goBack()}>
                <Image source={Images.close_modal}/>
              </TouchableOpacity>
            </View>
            */}
            <View style={styles.Left}>
              <Text style={styles.TituloInputOnBlur}>Cliente</Text>
            </View>
            <View style={styles.Center}>
              <ModalDropdown
                adjustFrame={style => {
                  style.top =(Platform.OS === 'ios' ? style.top : style.top - StatusBar.currentHeight);
                  return style;
                }}
                dropdownTextStyle={styles.dropdownTextStyle}
                dropdownTextHighlightStyle={styles.dropdownTextHighlightStyle}
                dropdownStyle={styles.dropdownStyle}
                defaultValue={'Seleccionar'}
                style={styles.dropStyle}
                textStyle={{
                  padding: 0,
                  margin: 0,
                  fontSize: rfv(16),
                  paddingVertical: hp('1.2%'),
                  fontWeight: 'normal',
                  fontStyle: 'normal',
                  textAlign: 'left',
                }}
                //onSelect={(index, value) => this.setState({SeleccionClientes: value})}
                //options={Object.keys(this.state.items)}
                onSelect={(index, value) => this.setState({SeleccionClientes: value})}
                options={Object.keys(this.items)}
              />
            </View>
            <View>
            {
              this.items[this.state.SeleccionClientes] != null ?
              <View>
                {
                  <FlatList
                    data={this.items[this.state.SeleccionClientes]}
                    renderItem={({item, index}) => (
                      <ListItem
                        containerStyle={{backgroundColor: '#fafafa', width: wp('87.1%'), height: 64, alignItems: 'center', justifyContent: 'center', alignSelf: 'center', marginTop: hp('2.8%'), paddingHorizontal: 0}}
                        topDivider={false}
                        bottomDivider={true}
                        titleStyle={{
                          marginLeft: 0,
                          fontSize: rfv(16),
                          fontWeight: "normal",
                          fontStyle: "normal",
                          textAlign: "left",
                          color: "#707070"
                        }}
                        subtitleStyle={{
                          marginLeft: 0,
                          fontSize: rfv(14),
                          fontWeight: "normal",
                          fontStyle: "normal",
                          textAlign: "left",
                          color: "#c4c4c4"
                        }}
                        title={`${item.name}`}
                        subtitle={`ID ${item.key}`}
                        switch={{
                          trackColor: { false: "#767577", true: "#81b0ff" },
                          thumbColor: item.fav == true ? "#1062cc" : "#f4f3f4",
                          ios_backgroundColor: "#9e9e9e",
                          value: item.fav, 
                          onValueChange: () => this.updateFav(item)
                        }}
                      />
                    )}
                  />
                }
              </View>
              :
              <View style={{alignItems: 'center', justifyContent: 'center', alignSelf: 'center'}}>
                <View style={{marginTop: hp('11%')}}>
                  <Image style={{marginBottom: hp('2.8%')}} source={Images.sad_face}/>
                </View>
                <Text style={{
                  fontSize: rfv(18),
                  fontWeight: "normal",
                  fontStyle: "normal",
                  textAlign: "left",
                  color: "#c4c4c4"
                }}>Sin proyectos activos</Text>
              </View>
            }
            </View>
          <View style={styles.BottomPush} />
        </KeyboardAwareScrollView>
        </View>
      </>
    );
  }
}

【问题讨论】:

    标签: javascript typescript react-native


    【解决方案1】:

    要解决此问题,您需要在 API response 和您的 own data 之间进行抽象,以便添加/删除数据(即:收藏夹)。

    为了让您的下拉列表显示一组客户端,您可以使用辅助函数:

    const buildOptions = () => {
       return items.reduce((output, current) => {
          const { client } = current;
          output.push(client);
          return output;
    }, []);
    };
    // returns: ['Walmart','Microsoft','Google']
    

    不幸的是,react-native-modal-dropdown 有一个限制,您不能在选项中使用idClient。因此,假设您的客户端名称是唯一的,您可以使用从客户端名称返回客户端 ID 的辅助函数,当用户进行选择时,该函数会在 onChange 属性中触发:

    const findClientIdByName = (name) => {
       return dropItems.find(item => item.client === name).idClient;
    }
    

    现在,当用户选择一些喜欢的项目时,过滤列表会更新为保存开关状态的特定属性(即:fav: true)。话虽如此,最初,fav 属性是undefined,这意味着开关将自动“关闭”。

    然后,您可以创建一个返回收藏项目的函数:

    const favoriteProjects = list.filter(item => item.fav);
    

    最后,在您的日历视图中,您可以像这样构建最终对象:

      const finalObject = { [selectedDate]: favoriteProjects };
    

    【讨论】:

      猜你喜欢
      • 2013-02-14
      • 2013-08-22
      • 1970-01-01
      • 2014-01-26
      • 2015-02-17
      • 1970-01-01
      • 2019-09-06
      • 2014-03-09
      • 1970-01-01
      相关资源
      最近更新 更多