如何在React功能组件中更改单击的映射项的类

发布时间:2020-07-07 15:07

我正在尝试在功能性React组件中的表中更改单击的排序元素的类(“升序” /“降序”)。 由于我正在映射表并检查全局状态,因此可以使用useState()查看当前要排序的列和选择的方向,但是如何更改 only 的类被单击的表项(为className sort-symbol-upsort-symbol-down)?不幸的是,setState对于功能组件是不可能的。

当前,它显然改变了所有排序按钮的排序图标的方向。

  const [direction, setDirection] = useState(false);
  const currentDirection = useSelector(state => state.direction);

  const handleClick = src=> {
    setDirection(prevState => !prevState);
    const params = {
      src,
      direction: direction == false ? "desc" : "asc"
    };
    dispatch(sort(params));
  };
  return (
    <table className="table">
      <thead>
        <tr>
          {columns.map((c, id) => (
            <th
              key={`id}`}
            >
              <button               
                onClick={() => handleClick(c.src)}
              >
                {c.label}
                <div
                  className={`sort-symbol-${
                    currentDirection == "asc" ? "down" : "up"
                  }`}
                ></div>
              </button>
            </th>
          ))}
        </tr>
      </thead>

谢谢!

回答1

最后,通过将ID传递给onClick事件找到了解决方案。然后分派并将其存储在状态中,以在呈现正确的排序符号之前进行检查:

const [direction, setDirection] = useState(false);
  const currentDirection = useSelector(state => state.direction);
  const selectedColumn = useSelector(state => state.selectedColumn);
  const handleClick = (src, id) => {
    setDirection(prevState => !prevState);
    const params = {
      src,
      direction: direction == false ? "desc" : "asc",
      id
    };
    dispatch(sort(params)); // the id is then dispatched to be stored in state 
  };
  return (
    <table className="table">
      <thead>
        <tr>
          {columns.map((c, id) => (
            <th
              key={`id}`}
            >
              <button      
               //passing the id to the onClick event        
                onClick={() => handleClick(c.src, id)}
              >
                {c.label}
                <div
                  className={`sort-symbol-${
                //checking state for the currently selected column before changing sort symbol
                    selectedColumn === id && currentDirection == "asc" ? "down" : "up" 
                  }`}
              </button>
            </th>
          ))}
        </tr>
      </thead>