简体   繁体   English

"我如何将样式仅应用于单击的元素 [React]"

[英]How can i apply style only to the clicked element [React]

I'm trying to apply conditional styles in React.<\/em>我正在尝试在 React 中应用条件样式。<\/em> I need to apply an animation when use click on delete button but this is applied to every element from the array<\/em>使用单击删除按钮时我需要应用动画,但这适用于数组中的每个元素<\/em>

Component<\/code>

import React, { useState } from 'react';

import './styles.css';

const Element = () => {
  const [onDelete, setOnDelete] = useState(false);
  const list = [
    {
      name: 'Jhon',
      age: '20',
    },
    {
      name: 'Maria',
      age: '25',
    },
  ];

  return (
    <>
      {list.map((item) => (
        <ul className={onDelete ? 'onDelete-apply' : ''}>
          <li>{item.name}</li>
          <li>{item.age}</li>
          <button onClick={() => setOnDelete(true)}>
            Delete
          </button>
        </ul>
      ))}
    </>
  );
};

export default Element;

You should be traking the element that it is clicked by its index, insted of true or false, on click you set the index of the clicked item in the state and then check if that index is the same as the index of the element when rendered您应该通过它的索引来跟踪它被点击的元素,设置为真或假,点击时您将被点击项目的索引设置为状态,然后检查该索引是否与渲染时元素的索引相同

import React, { useState } from 'react';

import './styles.css';

const Element = () => {
const [deletedIndex, setDeletedIndex] = useState(false);
      const list = [
        {
          name: 'Jhon',
          age: '20',
        },
        {
          name: 'Maria',
          age: '25',
        },
      ];
    
      return (
        <>
          {list.map((item, i) => (
            <ul key={i} className={deletedIndex === i ? 'onDelete-apply' : ''}>
              <li>{item.name}</li>
              <li>{item.age}</li>
              <button onClick={() => setDeletedIndex(i)}>Delete</button>
            </ul>
          ))}
        </>
      );
export default Element;

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

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