【发布时间】: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