0

所以我面临一个问题,我无法使用 useRef 更改 DOM 节点的宽度。我使用 onDragEnd 事件仅触发所选节点上宽度的更改。我通过更改 'elementRef.current.style.width 属性来设置宽度。但是这种变化并没有反映在前端。

这是我的代码:

import React, { useEffect, useState, useRef } from "react";
import timelineItems from "../timelineItems";
import "../index.css";

const TimeLine = () => {
  const [sortedTimeline, setTimelineSorted] = useState([]);
  const increaseDateDomRef = useRef(null);

  let usedIndex = [];

  useEffect(() => {
    let sortedResult = timelineItems.sort((a, b) => {
      return (
        new Date(a.start) -
        new Date(b.start) +
        (new Date(a.end) - new Date(b.end))
      );
    });

    setTimelineSorted(sortedResult);
  }, []);

  const increaseEndDate = (e) => {

  };
  const increaseEndDateFinish = (e, idx) => {
    //Im setting the width here but it is not being reflected on the page
    increaseDateDomRef.current.style.width = '200px';
    console.log(increaseDateDomRef.current.clientWidth);
  };

  return (
    <div className="main">
      {sortedTimeline.map((item, idx) => {
        return (
          <div key={idx}>
            <p>{item.name}</p>
            <p>
              {item.start} - {item.end}
            </p>
            <div className="wrapper">
              <div className="circle"></div>
              <div
                className="lineDiv"
                ref={increaseDateDomRef}
                draggable
                onDragStart={(e) => increaseEndDate(e)}
                onDragEnd={(e) => increaseEndDateFinish(e, idx)}
              >
                <hr className="line" />
              </div>
              <div className="circle"></div>
            </div>
          </div>
        );
      })}
    </div>
  );
};

export default TimeLine;
4

1 回答 1

1

首先,这可能不起作用,因为您对多个元素使用单个引用。

另一个帖子上的这个答案可能会对您有所帮助https://stackoverflow.com/a/65350394

但在你的情况下,我会做的是非常简单的事情。

const increaseEndDateFinish = (e, idx) => {
  const target = e.target;
  target.style.width = '200px';
  console.log(target.clientWidth);
};

您不必使用引用,因为您已经在事件目标上获得了引用。

于 2021-04-18T01:18:24.350 回答