我有一个演示组件,我想渲染一个基于类的组件,但我不想将其导入到演示组件中,我想将它作为属性传递。那可能吗?有更好的方法吗?
以下是我在其容器中渲染演示组件的方式,它的名称是 TodaysRevenueThumbnail:
renderTodaysRevenueThumbnail() {
if (!this.props.todaysTotalRevenue || !this.props.todaysSales) {
return <h1>Loading...</h1>;
} else {
return (
<TodaysRevenueThumbnail
totalRevenue={this.props.todaysTotalRevenue}
sales={this.props.todaysSales}
name={"Today's"}
ChartComponent={<TodaysRevenueChart/>}
/>
);
}
}
您可以看到我正在尝试向其传递另一个名为 TodaysRevenueChart 的组件的实例。
以下是我尝试在 TodaysRevenueThumbnail 中渲染 TodaysRevenueChart 的方法:
import React, {Component} from 'react';
const TodaysRevenueThumbnail = ({totalRevenue, sales, name, ChartComponent}) => {
return (
<div className="revenueThumbnail">
<div className="col-lg-12 col-md-12" >
<div className="thumbnail">
<ChartComponent todaysSales={sales} />
<div className="caption">
<h3>{name} Total Revenue: ${totalRevenue}</h3>
</div>
</div>
</div>
</div>
);
};
export default TodaysRevenueThumbnail;
我在控制台中收到错误消息:
“invariant.js:38Uncaught( promise 中)错误:元素类型无效:需要一个字符串(对于内置组件)或一个类/函数(对于复合组件),但得到:对象。检查渲染方法TodaysRevenueThumbnail
"
最佳答案
不要传递渲染的实例,而是传递组件构造函数:
<TodaysRevenueThumbnail
totalRevenue={this.props.todaysTotalRevenue}
sales={this.props.todaysSales}
name={"Today's"}
ChartComponent={TodaysRevenueChart}
/>
关于javascript - 我可以将基于类的组件作为属性传递给演示组件并让演示组件渲染它吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37977825/