reactjs - 将对象渲染为 React 组件

标签 reactjs components rendering

在我的实现中,我传递了一个reactelement(至少我是这么认为的)作为 Prop 。

我想将这个 prop 渲染为它自己的 React 组件,但浏览器提示它是一个对象。

澄清代码:

在父级中:

render() {
  return <SortableItem {...extraProps} item={React.cloneElement(item, extraProps)} />
}

item prop 包含我想要在 SortableItem 中渲染的元素

在 SortableItem 渲染中:

我想做这样的事情:

render() {
  return <props.item />
}

当我登录时props.item我明白了:

Object {$$typeof: Symbol(react.element), key: "item-5", ref: null, props: 
Object, type: function…}
$$typeof:Symbol(react.element)
key:"item-5"
props:Object
ref:null
type:function _class()

我很困惑为什么$$typeof会说这确实是一个 react 元素,但类型说它是一个 function _class()当我记录/渲染时,浏览器说它是一个对象。

这是我在渲染时在浏览器中遇到的错误 <props.item />SortableItem

Fatal Exception:Uncaught Invariant Violation: Element type is invalid: 
expected a string (for built-in components) or a class/function (for 
composite components) but got: object. Check the render method of 
`SortableItem`.(reload cancelled)

最佳答案

试试这个,

方法 1

在父级中:

render() {
  return <SortableItem {...extraProps} item={<YourComponent />} />
}

在 SortableItem 渲染中:

render() {
  return {this.props.item}
}

方法 2: 在父级中:

render() {
  return <SortableItem {...extraProps} >
     <YourComponent />
  </SortableItem>
}

在 SortableItem 渲染中:

render() {
  return {this.props.children}
}

关于reactjs - 将对象渲染为 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43584125/

相关文章:

javascript - 处理具有相同状态值的输入

reactjs - 基于 ULR Gatsby React 的隐藏/显示元素

javascript - 如何翻译 react-router 路由路径

iphone - 如何实现每天只显示一个组件的 UIDatepicker?

Objective-C 和组件编程

reactjs - 使用nextjs切换页面时如何只更改一个组件?

rendering - 如何修复模糊的 VS2019

javascript - 如何在 JavaScript 中生成简单的 3D 图像

ios - 在 React Native 中预渲染 ListView

delphi - 适用于 Delphi 2010 的 Amazon S3 组件