【问题标题】:Find the position of the React component in HTML在 HTML 中查找 React 组件的位置
【发布时间】:2021-03-09 05:14:04
【问题描述】:

元素被创建并附加在表格中,我想找到特定元素的位置, 我用过 UseRef 钩子,

const inputRef = useRef(null);

动态创建的样子

    return (
      <td style={{ margin: "1rem", padding: "1rem" }}>
        <Datetime
          ref={inputRef}
          closeOnSelect={true}
          dateFormat="MMM yy"
          timeFormat={false}
        />
      </td>
    );
  }

在 UseEffect 钩子中看起来像

我尝试了 OffsetTop 和 getBoundingClientRect。两者都没有帮助

    console.log(inputRef); //here no offsetTop is no there in current
    //console.log(inputRef.current.getBoundingClientRect());
  }, []);

outPut 在控制台中如下所示。

{current: n}
current: n
props: Object
context: Object
refs: Object
updater: Object
_renderCalendar: ƒ () {}
_showView: ƒ () {}
viewToMethod: Object
nextView: Object
_updateDate: ƒ () {}
_viewNavigate: ƒ () {}
_setTime: ƒ () {}
_openCalendar: ƒ () {}
_closeCalendar: ƒ () {}
_handleClickOutside: ƒ () {}
_onInputFocus: ƒ () {}
_onInputChange: ƒ () {}
_onInputKeyDown: ƒ () {}
_onInputClick: ƒ () {}
state: Object
_reactInternals: FiberNode
_reactInternalInstance: Object
isReactComponent: Object
setState: ƒ () {}
forceUpdate: ƒ () {}
<constructor>: "n"

如何获取当前ref元素的位置

我在沙盒中的代码:

【问题讨论】:

    标签: javascript reactjs use-ref


    【解决方案1】:

    <html>
    <head>
    <style>
    #test {
      top: 100px;
      margin: 10px;
      padding: 10px;
      width: 300px;
      position: relative;
      border: 5px solid black
    }
    </style>
    </head>
    <body>
    
    <div>Just another Div </div> <!-- Remove this to see the value change !-->
    <div>Just another Div </div> <!-- Remove this to see the value change !-->
    <span>Just another Span </span> <!-- Remove this to see the value change !-->
    
    <div id="test">
      <p>Click the button to get offsetTop for the test div.</p>
      <p><button onclick="myFunction()">Try it</button></p>
      <p>offsetTop is: <span id="demo"></span></p>
    </div>
    
    <script>
    function myFunction() {
      var testDiv = document.getElementById("test");
      document.getElementById("demo").innerHTML = testDiv.offsetTop;
    }
    </script>
    
    </body>
    </html>

    试试这个:offsetTop 每次都有效。

    编辑:

    对于列表,您可以将索引/计数器添加到元素的 ID 中,然后从 DOM 获取 ref 变得更加容易。 Sandbox Link for React Demo

    【讨论】:

    • 但问题是,当您根据返回的列表将组件添加到另一个组件中时,无法创建具有 id 的元素,因此,我们没有该元素 id,即使我们对 id 进行硬编码,然后在该循​​环中创建的所有元素都将使用相同的 id。如何在 React 中找到此类元素的元素位置
    • 我添加了一个演示,其中我正在遍历一个列表并为每个人添加一个唯一的 ID。这也应该适用于您的情况。如果您仍然无法从列表中获取 ref,则可以仅为您的代码创建一个沙箱。这样,我可以告诉您特定于您的代码的解决方案
    • 如果它对您有用,请考虑接受答案
    【解决方案2】:

    您可以通过 id 获取参考,然后可以应用 getBoundingClientRect()

    这是你的代码

    import Datetime from "react-datetime";
    import "./styles.css";
    import "react-datetime/css/react-datetime.css";
    import { useEffect, useRef } from "react";
    
    export default function App() {
      let table = [];
      const inputRef = useRef(null);
      useEffect(() => {
        let a = document.getElementById('input');
        console.log("answer",a.getBoundingClientRect()); //here no offsetTop is no there in current
        //console.log(inputRef.current.getBoundingClientRect());
      });
      function getRow() {
        return (
          <td style={{ margin: "1rem", padding: "1rem" }}>
            <div id="input">
            <Datetime
              ref={inputRef}
              closeOnSelect={true}
              dateFormat="MMM yy"
              timeFormat={false}
            />
            </div>.
          </td>
        );
      }
      function getRows() {
        let row = [];
        for (let index = 0; index < 6; index++) {
          row.push(getRow());
        }
        return <tr>{row}</tr>;
      }
    
      function getTable() {
        for (let index = 0; index < 10; index++) {
          table.push(getRows());
        }
        return table;
      }
    
      return (
        <div className="App">
          <table style={{ border: "solid 1px blue" }}>
            <tbody>{getTable()}</tbody>
          </table>
        </div>
      );
    }
    

    【讨论】:

    • 这对我没有帮助,假设我想知道我点击的日期时间选择器的位置,现在所有元素都将具有相同的 ID input。如何区分点击了哪个 DateTime Picker 并找到特定元素的位置?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 2014-03-08
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多