繁体   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