簡體   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