简体   繁体   English

在具有不同文本的不同html页面中多次渲染一个组件

[英]Render one component several times in different html pages with different text

I'm new to react and I'm trying to render one component in different html files (because I'm working in an existing project), each of them with different text. 我是新手做出反应,我正在尝试在不同的html文件中渲染一个组件(因为我在一个现有项目中工作),每个组件都有不同的文本。 I'm thinking of something like this: 我在考虑这样的事情:

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;

Then, in my index.js, I'm rendering like this, passing the props: 然后,在我的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);

I'm not sure if this is the best and simpler way to do this, because I'm calling ReactDOM.render twice for same component, and I got this error: 我不确定这是否是最好和更简单的方法,因为我为相同的组件调用两次ReactDOM.render,我得到了这个错误:

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

This works fine if I render the component once, but not for multiple instances. 如果我渲染一次组件,但是不是多个实例,这可以正常工作。 What is the best way to do it? 最好的方法是什么?

I've thought about this more, and I'm not experienced with adding React to existing websites, but here's what I'd suggest: 我已经考虑过这个了,而且我没有将React添加到现有网站的经验,但这是我建议的:

I would have 1 JS file per HTML page that imports CtaSection , each of those files would look like such: 我会在每个导入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);

You would just need to make sure each html page uses the corresponding JS file. 您只需要确保每个html页面都使用相应的JS文件。

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

Repeat for each page. 重复每页。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM