javascript - react : How to wait until ref is available when inserted (rendered) within a second container

标签 javascript reactjs react-hooks use-effect use-ref

编辑:更好的解释

上下文:

我从第三台服务器收到一些纯 HTML 代码,我想

  • 插入我的 React 应用程序
  • 修改

  • 原版 JS 方法
  • 我可以使用正则表达式修改字符串并添加任何带有 id 的 HTML 标记
  • 然后我可以通过getElementById修改这些元素, 像往常一样

  • React 方法
  • 我不应该使用 DOM
  • 然后我应该在字符串中插入一些在
  • 内有 React ref 的组件。
  • 相反(将一些 React 组件插入为纯 HTML)将通过 ReactDOMServer.renderToString
  • 所以,当我用 ReactDOM.render() 注入(inject)组件时,问题是 render方法需要时间,因此如果在下一行中我尝试使用插入组件中存在的 ref,则还没有

  • 问题
  • 怎么做?通常我会将代码放在 useEffect 中与 []依赖关系,但我在这里 rendering应用已挂载时的组件
  • 一个快速的解决方法是只进行 500 毫秒的异步等待,然后我可以访问 ref ,但肯定有更好的东西


  • 此代码失败,因为当 ref渲染它仍然不可用,所以 ref.current未定义

    我怎么能等到呢?

    codesandbox

    编辑:我提供了有效的代码,但通过直接 DOM,我认为应该避免

    import React, { useRef, useEffect } from "react";
    import ReactDOM from "react-dom";
    
    export default function App() {
      const myref = useRef();
    
      useEffect(() => {
        const Com = () => <div ref={myref}>hello</div>;
        ReactDOM.render(<Com />, document.getElementById("container"));
        console.log(myref.current); // undefined
        document.getElementById('container').textContent = "direct DOM works"
    
       // the next line fails since the ref is not yet available
       // myref.current.textContent = "but this REF is not available"; // fails
      }, []);
    
      const plainhtml = '<div><div id="container"></div><div>some more content</div><div id="another">even more content</div></div>'; // this is some large HTML fetched from an external server
    
      return (
        <div>
          <h1>Hello CodeSandbox</h1>
          <div dangerouslySetInnerHTML={{ __html: plainhtml }} />
        </div>
      );
    }
    

    最佳答案

    useEffect使用空依赖数组执行 之后 第一次渲染,因此您将在回调中获得 DOM ref:

    const htmlString = '<div id="container">Hello</div>';
    
    export default function App() {
      const myRef = useRef();
    
      useEffect(() => {
        if (myRef.current) {
          myRef.current.textContent = 'whats up';
        }
        console.log(myRef.current);
      }, []);
    
      return (
        <div>
          <div ref={myRef} dangerouslySetInnerHTML={{ __html: htmlString }} />
          <div dangerouslySetInnerHTML={{ __html: htmlString }} />
        </div>
      );
    }
    
    /* App renders:
    whats up
    Hello
    */
    

    Edit nervous-glade-8rtxb

    关于javascript - react : How to wait until ref is available when inserted (rendered) within a second container,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61408146/

    相关文章:

    javascript - NodeJS 无法异步发出 GET 请求

    javascript - 在 "store"的上下文中找不到 "Connect(MyComponent)"吗? Redux-React 问题

    material-ui - 使用 Hooks API 和 Enzyme 浅渲染测试 Material UI 组件

    reactjs - 使用 React Hooks 重新渲染的次数过多

    reactjs - 无法读取未定义的属性 'history'(React Router 5的useHistory钩子(Hook))

    javascript - ios 发送经纬度到WebView

    javascript - 将 Rails 表单 POST 数据传递给 JS 点击事件

    javascript - react 路由器相关链接没有正确链接

    html - 正确显示自动完成下拉列表的问题

    javascript - aloha 界面显示不正确(截图)