【问题标题】:Removing a border on the last element in a list React删除列表中最后一个元素的边框React
【发布时间】:2021-12-02 04:02:42
【问题描述】:

大家好,当列表增长到一定大小时,我正在尝试删除无序列表中最后一项的边框。我最初的想法是这样的:

document.querySelector('.employee-list-item:last-child').style.border = "none";

但是,React 说它不能将样式属性设置为“null”。它是否试图在渲染之前定位元素?有什么解决方法吗?

这是我的代码:

import "../css/Employee.css";
import Avatar from "./Avatar";
import React from "react";

const Employee = (props) => {
  // capitalize first letter of firstName and first letter of lastName
  const name = props.name
    .split(" ")
    .map((i) => i[0].toUpperCase() + i.slice(1))
    .join(" ");

  const { title } = props;

  return (
    <li className="employee-list-item">
      <Avatar name={props.name} />
      <span className={"employee-name"}>{name}</span>
      <span className={"employee-title"}>{title}</span>
    </li>
  );
};

export default Employee;

【问题讨论】:

  • 你编辑你的css,将样式添加到最后一项,.employee-list-item:last-child { YOUR STYLE }
  • 满足条件时有没有办法做到这一点?例如,如果列表增长到一定大小,我想删除边框,但我不想每次都删除边框。
  • 当列表具有您想要的条件时,您可以向您的 li 标签添加一个类 className="employee-list-item {yourCondition ?'Class' :''}"

标签: javascript reactjs


【解决方案1】:

创建一个名为“App.css”的新文件并在其中插入一些 CSS 代码:

您可以添加 CSS - Employee.css

.employee-list-item:last-child{border:none !important;}

在您的应用程序中导入样式表:

import './App.css';

【讨论】:

  • 是的,这对他有用
【解决方案2】:

您应该将代码放入一个 useEffect 钩子中 - 以确保它在 React 完成所有魔力并且虚拟 DOM 已渲染到实时 DOM 后运行。您已经想到的代码应该可以进行调整:

useEffect(() => {
    document.querySelector('.employee-list-item:last-child')[0].style.border = "none"; // or forEach(... if you expect more than one item to match
});

【讨论】:

    【解决方案3】:

    一种方法是将道具(例如 isLast)传递给 Employee 和基于此的样式。

    const Employee = (props) => {
      return (
        <li
          className="employee-list-item"
          style={props.isLast ? { border: "none" } : undefined}
        ></li>
      );
    };
    
    const List = () => {
      return (
        <div>
          {employees.map((emp, index) => (
            <Employee isLast={index === employees.length - 1} />
          ))}
        </div>
      );
    };
    

    【讨论】: