【问题标题】:Render a React element inside a React component在 React 组件中渲染一个 React 元素
【发布时间】:2016-10-17 20:37:31
【问题描述】:

好的,我正在尝试将我用作参数的对象内的组件传递给我正在触发的操作。

this.context.alt.actions.notificationActions.logMessage({
  component: <ModalLayoutEditorComments subscription="pop-up" contextualClass="info" callback={this._submitCaisseChangeAction} />,
  subscription: 'pop-up',
});

在目标组件中,我将对象作为道具接收到现在是 React Element 的组件。

现在我想知道如果可能的话,如何在另一个 React 组件中转换这个 React 元素?

  render() {
      const Component = this.props.notifications[0].component;

      return (
        <div>
          {Component}
        </div>
      );
  }

【问题讨论】:

  • 您的 render 方法看起来不错 - 这是渲染作为道具传递的元素的示例:jsfiddle.net/txqo702m/1
  • 在另一个 React 组件中使用 ReactDOM.render 可以吗?我尝试使用 React.cloneElement 没有运气。
  • 你不是在组件内调用ReactDOM.render 吗?组件 render 方法构建了一个 React 元素树,最终由应用根目录下的 ReactDOM.render 转换为 DOM 元素树。

标签: javascript reactjs components


【解决方案1】:

您的render 逻辑正常。看起来你使用了错误的道具:

render() {    
  return (
    <div>
      {this.props.notifications[0].component}
    </div>
  );
}

顺便说一句,component 是一个相当混乱的属性名称。该对象是一个 React 元素,即description of a Component instance。

【讨论】:

  • 您需要更具体吗?错误是什么?作为 props 传递的渲染元素是一种常见的 React 模式(例如{children})。 jsfiddle.net/txqo702m/1 对你有用吗?
  • 抱歉延迟了我没有定义所以我犯的错误是我没有使用导出默认 ModalLayoutEditorComments 导出组件。
【解决方案2】:

我得到的错误如下

元素类型无效:应为字符串(用于内置组件) 或类/函数(用于复合组件)但得到:未定义

我没有定义,因为我犯的错误是我没有使用 export default ModalLayoutEditorComments 导出组件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-19
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    • 2018-03-07
    • 2020-05-31
    相关资源
    最近更新 更多