簡體   English   中英

刪除基於React.js中的Click的數組的特定索引

[英]delete specific index of array based onClick in React.js

我有一行由一個文本框和一個按鈕組成。

單擊添加新行按鈕后,可以使用以下代碼添加這些行:

  1. useState: const [newSertifikasi, setNewSertifikasi] = useState(0)

  2. 加載一行: ...Array(newSertifikasi).map((i) => ("components here"))

  3. 添加新行: onClick={() => setNewSertifikasi(newSertifikasi + 1)}

我想創建一種通過單擊特定行中的按鈕來刪除行的方法。

我用過“拼接”和“過濾”的方法,但發現了死胡同

這是完整的代碼: https : //codepen.io/febry-aryo-riandhito/pen/BaRpNKQ

您可以像這樣使用splice通過索引刪除元素,函數可能更短,但為了理解,這是一個很好的解決方案。

function deleteByIndex(index){
     setNewSertifikasi(current => {
         const newArr = current;
         newArr.splice(index, 0);
         return newArr;
      })
}

一個較短的版本可能是這個

function deleteByIndex(index){
     setNewSertifikasi(current => [...current.splice(index, 1)])
}
let test = ['test01', 'test02', 'test03']

test.splice(1,1); // this delete specific index

console.log(test) // ['test01', 'test03']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM