繁体   English   中英

更新数组 javascript 索引上的数据并做出本机反应

[英]Updating data on an index of a array javascript and react native

在我的 Todo 应用程序中,我已经成功实现了添加和删除功能,但是更新 function 遇到了问题。 我需要它做的是,当我单击 Todo 的可触摸不透明度时,它应该出现在我的输入框中,如果进行了任何更改,则应该更新该 todo,例如单击 abcd 必须使其出现在输入框中并进行更改它应该被更新。 下面还添加了图片在此处输入图像描述

export default function Todo() {
  const [getText, setText] = useState('');
  const [getList, setList] = useState([]);

  const addItem = () => {
       setList([...getList, {key: Math.random().toString(), data: getText}]);
       setText('');
    }

  const removeItem = (itemKey) => {  
    setList(() => getList.filter(item => item.key != itemKey));
  }

  const updateFieldChanged = (index) => e => {
    let newArr = [...getList]; // copying the old datas array
    newArr[index] = e.target.value; // replace e.target.value with whatever you want to change it to
    setList(newArr);
}

  return (
    <View style={styles.container}>
      <Text style={styles.title}>todo</Text>
      <View style={styles.inputContainer}>
        <TextInput
          style={styles.textInput}
          placeholder="Enter Item"
          onChangeText={text => setText(text)}
          value={getText}
        />
        <CustomButton     
          text = 'add'
          color='red'
          title= 'add'
          textSize={20}
          textColor="white"
          onPressEvent={addItem}

        />
      </View>

      <ScrollView style={styles.scrollview}>
        {getList.map((item, id) =>
          <TouchableOpacity
            key={item.key}
            activeOpacity={0.7}
            onPress= {() => updateFieldChanged(id)}


          >
            <View style={styles.scrollviewItem}>
              <Text style={styles.scrollviewText}>{id}) {item.data}</Text>
                <TouchableOpacity
                  onPress={() => removeItem(item.key)}
              >
                <View style={styles.crosstextcontainer}>
                  <Text style={styles.crosstext}>X</Text>
                </View>
              </TouchableOpacity>


            </View>
          </TouchableOpacity>
        )}
      </ScrollView>
    </View>
  );
}

改变

  <TouchableOpacity
            key={item.key}
            activeOpacity={0.7}
            onPress= {() => updateFieldChanged(id)}
          >

  <TouchableOpacity
              key={item.key}
              activeOpacity={0.7}
              onPress= {() => updateFieldChanged(id,getText)}
            >

在这里,我传递了您需要输入以更新特定字段的文本

像这样更改您的updateFieldChanged

  const updateFieldChanged = (index, text) => {
      let newArr = [...getList]; // copying the old datas array
      newArr[index].data = text; // replace e.target.value with whatever you want to change it to
      setList(newArr);
      setText('');
  }

这里我将您在 TextInput 中输入的文本分配给数据 object,这将更新数组。

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM