【问题标题】:How can you change the class of clicked mapped item in a React functional component如何更改 React 功能组件中单击的映射项的类
【发布时间】:2020-10-27 21:22:54
【问题描述】:

我正在尝试更改功能性 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>

谢谢!

【问题讨论】:

    标签: reactjs redux use-state react-functional-component


    【解决方案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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-24
      • 2022-11-30
      • 2020-06-22
      • 2018-06-08
      • 2021-04-14
      • 1970-01-01
      • 1970-01-01
      • 2021-04-06
      相关资源
      最近更新 更多