【问题标题】:How to add and subtract list data in state on checkbox check and unchecked in react native如何在复选框选中状态和未选中状态下添加和减去列表数据反应本机
【发布时间】:2019-08-13 09:30:53
【问题描述】:

在此屏幕中,我正在使用复选框映射数组(“数组上方)值,有一些“data.TransactionAmount”我必须计算所有的总和并发送到下一个屏幕, 但是如果我取消选中任何列表金额应该减去。就像有 3 个值 - 1050+1050+1050 =3150,如果我取消选中单个值,那么它应该是 1050+1050-1050=2100 并且它应该在下面的按钮中更新。 如果我取消选中单个列表,则所有列表都将被取消选中。 在“总和”状态下,我得到的总和是默认值,并且值将出现在按钮中。但如果我取消选中任何列表,值应该减去。 请帮忙,谢谢, 下面的链接是我正在实施的参考。

https://xd.adobe.com/view/d733da48-5d0c-47ca-7ded-6fc8f0f609cf-a102/screen/37cb15c6-b56a-4b98-8612-e9b86d0dd34c/Android-Mobile-147/?fullscreen

 // Below is the array value 
    financialTransactionDetail: Array(3)
    0:
    AdjustedAmount: "0"
    NetTransactionAmount: "1050"
    TransactionAmount: 1050
    1:
    AdjustedAmount: "0"
    NetTransactionAmount: "1050"
    TransactionAmount: 1050

    2:
    AdjustedAmount: "0"
    NetTransactionAmount: "1050"
    Status: "Unpaid"
    TransactionAmount: 1050

    this.state = {
          title: 'Payments against invoice',
          icon: 'sim',
          mobile:navigation.state.params.customer.service.serviceNumber,
          isChecked:true,
          sum :financialTransactionDetail.financialTransactionDetail.reduce((a, c) => { return a + c.TransactionAmount}, 0),
          transactionAmount :''
        }

         handleChange(key , value){

        this.setState({
          isChecked:!this.state.isChecked})
      }

      handleChangeSum = (sum) => {
        this.setState({
          sum: sum
        });
      }

     { !_.isEmpty(financialTransactionDetail.financialTransactionDetail) && financialTransactionDetail.financialTransactionDetail.map(
                        (data, index) => {
                          return(
                            <View key={index} style={{flexDirection:'row', padding:10, alignItems:'center', justifyContent:'space-between'}}>
                          <View style={{paddingRight:10, marginRight:10}}>
                            <CheckBox style={styles.checkBox} color="#00678f" checked={this.state.isChecked} onPress={() =>this.handleChange()}/>
                          </View>
                          <View style={{flexDirection:'column',flex:1, padding:10, borderWidth:1, borderColor:'lightgrey', borderRadius:10}}>
                            <View style={{flexDirection:'row', alignItems:'center'}}>
                              {!this.state.isChecked && <RegularText text={`₦ ${data.TransactionAmount}`} style={{paddingBottom:10, paddingRight:5}}/>}
                              <SmallText text="From 1-Jan-2019 to 31-Jan-2019" style={{paddingBottom:10}}/>
                            </View>
                            {this.state.isChecked && 
                            <RegularText text={`₦ ${data.TransactionAmount}`} style={{borderColor: '#00fff', borderBottomWidth:1}}>
                              </RegularText>
                            }
                          </View>
                        </View>
                          )
                        }
                      )
                      }

                      <View>
                  <Button full onPress={()=>navigation.navigate('PaymentOptionsContainer',sum)}>
                    <Text>Receive Payment ({sum})</Text>
                  </Button>
                </View>

谢谢

【问题讨论】:

  • 我看到还有更多答案,所以我把链接放在这里:stackblitz.com/edit/react-nyalzx
  • 非常感谢.. 但是这个数组值会动态出现
  • 没问题。在某些时候,它将处于组件的状态,因此它会像在 sn-p.. 中一样工作。
  • 谢谢。让我也试试 :)
  • 我稍微更新了 sn-p。也许现在更合适。

标签: javascript reactjs react-native ecmascript-6


【解决方案1】:

而不是 isChecked 使用已检查的数组,如下所示

// Instead
isChecked: true
// Use below one
checked: financialTransactionDetail.map(() => true)

现在让复选框根据下面的索引指向

// Instead
<CheckBox style={styles.checkBox} color="#00678f" checked={this.state.isChecked} onPress={() =>this.handleChange()}/>
// Use Below one
<CheckBox style={styles.checkBox} color="#00678f" checked={this.state.checked[index]} onPress={() =>this.handleChange(index)}/>

现在更改复选框的 onchange 句柄

handleChange(index){
  let newChecked = [...checked];
  newChecked[index] = !newChecked[index];
  this.setState({checked: newChecked})
}

最后根据校验数组计算总和

let sum = 0;
this.state.checked.map((value, index) => {
  if(value) {
    sum += financialTransactionDetail[i].TransactionAmount;
  }
});

【讨论】:

  • 得到错误“检查:financialTransactionDetail.map(() => true)
  • financialTransactionDetail.map 不是函数
  • 勾选:financialTransactionDetail.financialTransactionDetail.map(() => true)
  • 我也意识到了,让我试试
  • 让 sum = 0; this.state.checked.map((value, index) => { if(value) { sum += financialTransactionDetail[i].TransactionAmount; } });
【解决方案2】:

您的代码似乎与库和专有代码密切相关。

我确定您只是在寻找一些有助于在检查/取消检查金额时更新总余额的方法。

这是我为您制作的可以复制的工作沙箱:https://codesandbox.io/s/zen-swanson-2ccxo

工作代码:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const data = [{ amount: 1050 }, { amount: 1025 }, { amount: 1000 }];

class App extends React.Component {
  state = {
    data: [],
    total: null
  };

  componentDidMount() {
    const dataWithCheckedProp = data.map(item => {
      return { ...item, checked: true };
    });

    let total = data.reduce((total, item) => total + item.amount, 0);

    this.setState({
      data: dataWithCheckedProp,
      total: total
    });
  }

  handleOnChange = index => {
    const dataCopy = [...this.state.data];

    dataCopy[index].checked = !dataCopy[index].checked;

    let balance = dataCopy.reduce((total, item) => {
      if (item.checked) {
        total = total + item.amount;
      }
      return total;
    }, 0);

    this.setState({
      data: dataCopy,
      total: balance
    });
  };

  render() {
    const { data, total } = this.state;
    return (
      <div>
        {data.map((item, index) => {
          return (
            <div>
              <input
                type="checkbox"
                checked={item.checked}
                onChange={() => this.handleOnChange(index)}
              />
              <label>{item.amount}</label>
            </div>
          );
        })}
        <h4>Total: {total}</h4>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

总之,您需要采取以下步骤:

  1. 你真的只需要给每个对象 financialTransactionDetail 数组 checked 属性。见逻辑 在componentDidMount() 中,我们克隆金融数据数组并为每个对象赋予一个新属性。
  2. 在你的变更处理函数中,让它接受一个index,它 指的是被切换的项目。 index 将通过 .map() 的第二个参数。见handleOnChange()logic
  3. handleOnChange() 内,使用index 查找其中的对象 数据集并简单地切换其checked 布尔值。然后 使用更新后的数组,只添加您的 .reduce() 函数 那些被检查的项目。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-08
    • 2021-03-11
    • 1970-01-01
    • 2015-05-21
    • 2016-06-19
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多