如何渲染作为 Prop 传入的 StyledComponent
?
我将 Spinner
组件传递到我的 BarComponent
作为渲染 Prop 。在下面的示例中,我尝试在我的 BarComponent
中使用 {this.props.icon}
但它给了我一个错误:
Objects are not valid as a React child (found: object with keys {$$typeof, render, attrs, componentStyle, displayName, foldedComponentIds, styledComponentId, target, withComponent, warnTooManyClasses, toString}). If you meant to render a collection of children, use an array instead.
我该如何解决这个问题?
import React, { Component } from 'react';
import { StyledIcon } from 'styled-icons';
import { Spinner } from 'styled-icons/fa-solid';
interface BarComponentProps {
icon: StyledIcon,
name: string
}
class BarComponent extends Component<BarComponentProps> {
render() {
return (
// How to render a StyledComponent passed in as a prop?
// In this example it should result in something like:
// <div><Spinner /> - {this.props.name}</div>
<div>{this.props.icon} - {this.props.name}</div>
);
}
}
class FooComponent extends Component {
render() {
return <BarComponent icon={Spinner} name='Baz' />;
}
}
最佳答案
您可以使用 createElement()
,如下所示:
<div>{React.createElement(this.props.icon)} - {this.props.name}</div>
关于reactjs - 渲染一个作为 Prop 传入的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53715631/