簡體   English   中英

如何在 Array.map(), REACT.JS 中操作一個元素而不影響其他元素

[英]How To Manipulate One Element Without Effecting The others in Array.map(), REACT.JS

我想在單擊按鈕時更改元素的樣式,但我無法弄清楚如何在不更改數組中所有未單擊元素的樣式的情況下執行此操作。

        <div >
            {props.stuff.map(item => 
                <li className={itemClass}>
                    <div>{item}</div>
                    <button onClick={...change the style of the <li> without effecting the others}>Done</button>
                </li>)}
        </div>

我在想我需要給每個 li 一個唯一的 ID 並在我的 click Handler 函數中訪問該 ID,並將另一個 css 類應用到只有具有該 ID 的 li ......但我不知道如何做到這一點。 或者我可能走錯了方向。 任何建議將不勝感激!

你可以嘗試這樣的事情:

const handleClick=(e)=>{
        e.preventDefault();
        e.target.style.color = 'red'
    }

<button onClick={(e) => handleClick(e)}>Done</button>

不確定這是“最好的方法”,因為我自己不是前端開發人員,但是您可以將li創建為單獨的組件,然后使用 React 的useState鈎子。 例如:

/* your file */
<div>
  {props.stuff.map(item => <MagicLi>{item}</MagicLi>)}
</div>
/* separated component file */
import React, { useState } from 'react';

function MagicLi(props) {
  
  const [color, setColor] = useState('li-orange');

  const changeColor = function() {
    if (color === 'li-orange') setColor('li-green');
    else setColor('li-orange');
  };

  return (
    <li className={color}>
      <div>{props.children}</div>
      <button onClick={changeColor}>Done</button>
    </li>
  );
}

export default MagicLi;
/* add to your css file the styling you want */
.li-orange {
  color: orange;
}

.li-green {
  color: green;
}

由於您正在通過stuff.map迭代集合, stuff.map您可以將條件樣式應用於所需的元素。 不需要id

例如:

const [clickedIndex, setClickedIndex] = useState(null)
const specialStyle = { ...someStyles }

<div >
  {props.stuff.map((item, index) => 
    <li className={itemClass} style={index === clickedIndex ? specialStyle: null}>
      <div>{item}</div>
      <button onClick={() => setClickedIndex(index)}>Done</button>
    </li>)}
</div>

為了擴展上述答案,它僅限於一個特殊顏色的li標簽。 如果每個li標簽都需要跟蹤它自己的特殊顏色狀態,那么一個新組件將是一個很好的方法,它渲染一個li並跟蹤它自己的狀態。

例如:

{props.stuff.map((item, index) => <CustomLI key={index}/>)

const CustomLi = (props) {
   ... state & render stuff
}

暫無
暫無

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

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