【问题标题】:Render one component several times in different html pages with different text用不同的文本在不同的 html 页面中多次渲染一个组件
【发布时间】:2019-05-21 15:25:17
【问题描述】:

我是新手,我正在尝试在不同的 html 文件中呈现一个组件(因为我在现有项目中工作),每个组件都有不同的文本。 我正在考虑这样的事情:

class ctaSection extends React.Component{

   render(){
       return(
           <div className="cta-section">
           <div className="md:w-9c">
               <h5 className="uppercase">{this.props.h5}</h5>
               <h3>{this.props.h3}</h3>
           </div>
           <div className="cta-button">
               <a href="#">
                   <button className="w-full">{this.props.button}</button>
               </a>
           </div>
       </div>
       );
   }

}

export default ctaSection;

然后,在我的 index.js 中,我像这样渲染,传递道具:

let ctaPage1 = document.getElementById('cta-section-page-1');
let ctaPage2 = document.getElementById('cta-section-page-2');
ReactDOM.render(<CtaSection h3='my text for page 1' h5='my h5 for page 1' button='hello'/>, ctaPage1);
 ReactDOM.render(<CtaSection h3='text for page 2' h5='something' button='click me'/>, ctaPage2);

我不确定这是否是最好和更简单的方法,因为我为同一个组件调用 ReactDOM.render 两次,我得到了这个错误:

Uncaught Invariant Violation: Target container is not a DOM element.

如果我渲染一次组件,这很好用,但不适用于多个实例。 最好的方法是什么?

【问题讨论】:

  • 我不确定 React 如何处理多个 html 页面,但看起来您的 index.js 文件不知道它在哪个 html 页面上,所以其中一个 document.getElementByIds 将找不到任何东西。我假设这些元素中的每一个都在不同的页面上。

标签: javascript html reactjs jsx


【解决方案1】:

我对此进行了更多的考虑,但我没有将 React 添加到现有网站的经验,但我的建议如下:

每个导入 CtaSection 的 HTML 页面会有 1 个 JS 文件,每个文件看起来像这样:

// page1.js
import CtaSection from '../CtaSection'; // or wherever it is

let ctaPage = document.getElementById('cta-section-page');
ReactDOM.render(<CtaSection h3='my text for page 1' h5='my h5 for page 1' button='hello'/>, ctaPage);

您只需要确保每个 html 页面都使用相应的 JS 文件。

// page1.html 
<body>
    <div id="cta-section-page"></div>
    <script src="page1.js"></script>
</body>

对每一页重复。

【讨论】:

  • 是的,我认为这是我的错误,将 reactDOM.render 添加到同一个 index.js 文件两次,因为这个文件是我在 webpack 配置中唯一的 js 入口点......但是添加它到不同的js文件解决问题,谢谢
猜你喜欢
  • 2016-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-17
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
相关资源
最近更新 更多