reactjs - 渲染一个作为 Prop 传入的组件

标签 reactjs typescript styled-components

如何渲染作为 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/

相关文章:

javascript - 当React 16中不推荐使用 `mainPanel`时,如何使用 `this.refs`?

typescript - 如何在电容器的 Electron 结构中使用opencv.js? ReferenceError : cv is not defined

typescript - 预期对象是一种标量可观察对象,但它是可观察对象

reactjs - Typescript Utils 类返回 React 组件

css - styled-components, polished and styledProps - darken() 抛出错误

css - 容器问题 - React 和样式化组件

javascript - 对象作为具有样式化组件的 React 子项无效

javascript - React Router - 除了使用 Context 之外,还有 'easier' 路由到新路径的方法吗?

javascript - 使用 Material UI 访问 renderValue 组件上的 react 事件处理程序时出现问题

javascript - 为什么它们有不同的尺寸? (next/image & img html 元素)