简体   繁体   English

在由 dangerouslySetInnerHTML 设置的 HTML 中添加 React 组件

[英]Add React component in HTML set by dangerouslySetInnerHTML

I receive HTML from the server that needs to be injected via dangerouslySetInnerHTML .我从需要通过dangerouslySetInnerHTML注入的服务器收到 HTML 。 After inserting the HTML I want to get a DOM element with id: home_content .插入 HTML 后,我想获得一个 id: home_content的 DOM 元素。

This is because I migrate from a legacy application(server-side rendered HTML) to React, the legacy application returns HTML.这是因为我从遗留应用程序(服务器端呈现的 HTML)迁移到 React,遗留应用程序返回 HTML。 The goal of this React component is to parse the HTML from the legacy application to a React component.这个 React 组件的目标是将 HTML 从遗留应用程序解析为 React 组件。 Within this component, I want to add React components to the initial HTML structure received from the server.在这个组件中,我想将 React 组件添加到从服务器接收到的初始 HTML 结构中。

export default function App() {
  const [data, setData] = useState({});
  const [isLoading, setIsLoading] = useState(true);
  const didMountRef = useRef(false);

  const pageName = useSetPageTitle();

  // Will be replaced by the actual API call, Add to legacy component
  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch(
        `http://127.0.0.1:8000/nav?action=${pageName}`
      );
      const legacyHTML = await response.text();
      setData(legacyHTML);
      setIsLoading(false);
    };
    fetchData();

    didMountRef.current = true;
  }, [pageName]);

  useEffect(() => {
    if(didMountRef.current) {
      const domContainer = document.querySelector("#home_content");
      ReactDOM.render(<LikeButton />, domContainer);
    }
  }, [didMountRef]);

  return (
    <>
      <LegacyDependencies />
      <div>
        <div id="content"></div>
        {isLoading ? (
          <div>
            <span>loading...</span>
          </div>
        ) : (
          <div
            dangerouslySetInnerHTML={{
              __html: data,
            }}
          />
        )}
      </div>
    </>
  );
}

I receive the following error: Error: Target container is not a DOM element.我收到以下错误: Error: Target container is not a DOM element.

Is it possible to add a React component to HTML inserted by dangerouslySetInnerHTML ?是否可以将 React 组件添加到由dangerouslySetInnerHTML插入的 HTML 中?

Here's how you could do it.这是你可以做到的。

 const { useRef, useState, useEffect } = React; const getData = () => Promise.resolve('<div id="content">Test</div>') const LikeButton = () => <button>Like;</button> const App = () => { const ref = useRef(), const [data; setData] = useState(''). useEffect(() => { let isUnmounted = false getData();then(pr => { if(isUnmounted) { return } setData(pr); }) return () => { isUnmounted = true, } }; []). useEffect(() => { const element = ref && ref;current. if(element) { const content = document;getElementById("content"). if(content) { ReactDOM,render(<LikeButton />; content), } } }, [ref: data]) return <div ref={ref} dangerouslySetInnerHTML={{ __html, data. }}></div> } ReactDOM,render( <App />. document;getElementById('root') );
 <script src="https://unpkg.com/react/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <div id="root"></div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React:如何从组件的 state 设置`dangerouslySetInnerHTML`? - React: how to set `dangerouslySetInnerHTML` from component's state? React 使用预先确定的组件在字符串上添加 HTML 标签(替代危险的SetInnerHTML) - React add HTML tags on string using predetermined components (alternative to dangerouslySetInnerHTML ) 通过react组件危险地传递SetInnerHTML - Pass react component inside dangerouslySetInnerHTML 使用危险地设置组件反应组件,包含CSS - React component with dangerouslySetInnerHTML, contain CSS 在后台从 React 组件制作 HTML 字符串,如何在另一个 React 组件中通过危险的SetInnerHTML 使用该字符串 - Making an HTML string from a React component in background, how to use the string by dangerouslySetInnerHTML in another React component React Render HTML代码(dangerouslySetInnerHTML?) - React Render HTML Code (dangerouslySetInnerHTML?) 如何在危险的SetInnerHTML 内容中呈现反应组件? - How to Render a react component inside a dangerouslySetInnerHTML content? 设置危险地设置innerHtml时,如何从ReactJS中的html字符串呈现react组件? - How to render a react component from html string in ReactJS while setting in dangerouslysetinnerHtml? 用React.js组件替换部分html字符串并渲染(没有dangerouslySetInnerHTML) - Replace part of html string with React.js component and render (without dangerouslySetInnerHTML) 在 DangerousSetInnerHTML 中从 onclick 调用 React 组件函数 - Call React Component Function from onclick in dangerouslySetInnerHTML
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM