如何从DOM节点创建react组件?

问题描述 投票:0回答:2

我想从DOM节点创建一个react组件(非常小,没什么了不起的),例如:

//this footer is plain html and css, not a react component
const Footer = document.getElementById("#anAwesomeFooter")

并以某种方式在我的应用程序的任何地方使用它:

// before doing some magic
<Main>
 <Footer />
<Main />
reactjs dom react-component
2个回答
0
投票

我认为你可以获得的壁橱是在componentDidMount中获取DOM节点的内容,并将其附加到渲染元素。这个问题和答案是相关的。 https://stackoverflow.com/a/53897595/4703833


0
投票

import React from 'react';

const Footer = () => (<div>Footer of some div outside the Main component hierarchy</div>);

const SomeComponent = () => {
  const elementToAttach = document.getElementById('someElementId');
  return (
    <Main>
      {React.createPortal(Footer, this.elementToAttach)}
    </Main>
  );
};

您可以在构造函数中执行getElementById只运行一次,但这取决于您是否知道该元素已经被渲染

© www.soinside.com 2019 - 2024. All rights reserved.